Parsing text file and output to text file or csv

5353
6
Jump to solution
06-20-2016 08:46 AM
KushendraShah1
New Contributor III

Hi

I have a gps text file that has coordinates with other variables. I need to parse the file in order to get Lat, Long and Altitude values from the file and write it into new text file or csv. I tried to read the lines but I got error like this:

Here is my code:

# This script reads a GPS data and prints a list of coordinate pairs

import csv

# Set up input

gpsdata = open("C:/testdata/telemetry2.txt", "r")

# Set and process CSV reader

csvReader = csv.reader(gpsdata)

header = csvReader.next()

latvalueIndex = header.index("lat")

lonvalueIndex = header.index("long")

altvalueIndex = header.index("alt")

# Make an empty list

coordList = []

# Loop through the lines in the file and get each coordinate

for row in csvReader:

    lat = row[latvalueIndex]

    lon = row[lonvalueIndex]

    alt = row[altvalueIndex]

    coordList.append([lat,lon,alt])

# Print the coordinate list

print coordList

I have also attached the data sample. I will appreciate for any help to get this fixed. Thanks

0 Kudos
1 Solution

Accepted Solutions
RebeccaStrauch__GISP
MVP Esteemed Contributor

Do you have NotePad++   (free Notepad++ v6.8.2 )

You can easily replace the tabs with commas with that.  There are also ways to do it with Word (a tab is ^t I believe).

Or in python

aRecord.replace("\t", ",")

View solution in original post

6 Replies
DanPatterson_Retired
MVP Esteemed Contributor

well there are no commas for the csv (comma, separated values) reader to separate on.  Can you not just parse this using spaces?

0 Kudos
KushendraShah1
New Contributor III

Dan, the data is tab delimited, the script works when you insert commas between columns. I was thinking if there is solution that directly read and write tab delimited data or like this type. Thanks

0 Kudos
DanPatterson_Retired
MVP Esteemed Contributor

well a spreadsheet can, but I presume you tried that already, otherwise you will have to parse on the tabs

RebeccaStrauch__GISP
MVP Esteemed Contributor

Do you have NotePad++   (free Notepad++ v6.8.2 )

You can easily replace the tabs with commas with that.  There are also ways to do it with Word (a tab is ^t I believe).

Or in python

aRecord.replace("\t", ",")

TedKowal
Regular Contributor II

Would this be of any help? ..... I have use this for tab delimited files (excel style).

13.1. csv — CSV File Reading and Writing — Python 2.7.12rc1 documentation

Just be sure you have:

1. No ASCII Null Data

2. UTF-8 Format or ASCII printable  delimiters

import csv
reader = csv.DictReader(open('somefile.txt', 'rb'), delimiter='\t')
for row in reader:
  #do something more useful here
  print row.get('new')
KushendraShah1
New Contributor III

Thanks Dan Petterson, Rebecca Strauch and Ted Kowal for your inputs. Appreciated. It is solved now.

0 Kudos