[Tutor] Reading a csv of coordinates, trying to write a csv of bearings.

Gregory Lund gnj091405 at gmail.com
Mon Jul 9 03:10:11 CEST 2012


I'm Not looking for an absolute solution, but perhaps some insight
into some snippets of code, or
	suggestions of where I should seek out answers to this issue.
Or where I've gone wrong below.
NOTE: currently this 'code' below reads my file and writes a file, but
what it's doing in the middle isn't what it's supposed to do (I know
that!) I just modified what I had to at least read/write, now I need
to add the atan2() stuff.

I'm currently reading 'learning python' (Lutz) for 2.6 (not 3.0!)
I must use 2.6 because that is what esri's ArcGIS 10.0 uses.
I'm Doing (1/2 way through)  the non-programmers tutorial for python
2.6, hoping to 'graduate' to the
http://docs.python.org/release/2.6.8/tutorial/index.html once I get
through the non-programmers tutorial.

Objectives: read a CSV file of coordinates, and generate a
    	new CSV file of bearings.

Provided: A valid CSV file with coordinates (every other line blank,
if that matters)

Intended result: A valid CSV file with bearings

Logic?: one function, accepting a filename for the input, and a filename
	for the output (i.e. Coord_to_bearing(infile, outfile))

Caveats:
	A bearing is declination from north (meaning the angle between the
            direction and north).
	2 points define a line (y = mx + b). (obviously)
	Supposedly atan2() (from import math) will be in the code
	http://en.wikipedia.org/wiki/Atan2

Sample input:
	0,1,1

	1,2,2

	2,3,3

	3,4,3

	4,1268144.125,226540.2969
		
	5,1268463.75,226260.1563


Sample output:
        OID1,OID2,ANGLE
	0,1,45.0
	1,2,45.0
	2,3,90.0
	3,4,?
	4,5,?
	

Since I am a beginner, I re-used some code from a previous task, and
kept lots of it
	commented out to use to help with future coding.
Partial Code written in pursuit of this goal (with limited success)
	it's messy, and incorrect, but it's a start, maybe hurting more than helping.

'''
The code herin was initially written to find a nmea sample file
('nmea_sample.txt) within the same folder as this .py file.
It has been modified to read the giveN CSV file of coordinates, and
generate a new CSV file of bearings.

Python will try to find the first parameter (ie, coordinates.csv) in
the same folder in which the .py file is saved.
The second parameter is the output that will be saved in the same
folder automatically.
Put another way... The new .csv file will be saved to the same folder
in which  .py file is saved.
    I could use user input but trying to keep it simple.


1 Define a function that will be run (he name of the file, in the
working directory so that Python
    knows what file to find, and where.
2. open the file
3. "line' = f.readline()" establishes 'line' and reads/returns one line from f's
    file, up to the end of the line.
4. read the file line by line (while loop)
5. assigning 'data' as splitting the line by commas (',')
6. Extract information by line
7. Calculating the Bearings #this step is missing
8. Creating a new CSV file.

# I left lots of comments and 'old' code in so that I could use this
as a learning experience.


'''
import math     #importing math so that atan2 is available
#1 Establishing the filenames

def coord2bearing(coordFile,csvFile):   # defining a function that
will be used later, a return is required at the end when function is
done.
                                        # these two parameters will be
filled when calling this function in the python Shell.
    import csv #2importing the csv module that has the necessary tools
I need to read/create a csv file.

    csv_writer = csv.writer(open(csvFile, 'wb'), delimiter = ',') #
not sure if I need the ',' in here yet?.
                                                                  #
creating a csv file by using csv module's tool called 'writer' and
'open';
                                                                  #
'csv_writer' is just a variable name that could be anything
                                                                  #
defining 'csv_writer' as an object that has attributes and tools
                                                                  #
Important Note: Using 'wb' instead of 'w' caused the csv file to have
line breaks.
    myfile = open (coordFile) # open the original sample data file by
using the open function (coordinates2.csv) (original coordinates.csv
had blank lines)
    filename = 'coordinates.csv'

    #2 The 'open()' command opens the extablished filename.
    f = open(filename)

    #3 applying 'line' and the f.readline statement

    line = f.readline() #3

    #4 read the file line by line in a 'while' loop.
    OID = 0 # setting the OID varible to zero
    while (line): #...while there is a line to go to...

    #5 assigning 'data' as splitting the line by commas (',')

        data = line.split(',') #not sure yet how the .csv is read, if
it 'sees' a comma or not...?

        if data[0] >= 0: #6just using this to keep indents the same as
previous use of this code as I play with it. should perhaps have it
test 'is string?' then quit.

            #Latitude
            lat_init = data[2] # initial latitude is the third item,
(3-spot in the csv line)
            y = float(lat_init) #Lat Degrees

            #Longitude
            long_init = data[1] # initial longitude is in the 2nd item
(1-spot in the csv line)
            x = float(long_init) #Long Degrees


            #7 Missing: Need to figure out how to convert the
coordinates to a bearing...
            radians = math.atan2(y, x) #aTan2 provides Radians
            degrees = radians*(180/math.pi)
            # Write results to a file
            csv_writer.writerow([OID,float(y),float(x),degrees]) # 8
write OID,y value, x value, degrees (currently) to the csv file.

            OID += 1

    #read the next line so the loop can restart
        line = f.readline()
    f.close()
    myfile.close() #should close 'myfile'.
    return # finish the initial 'def' function line 1

#the following was added so that the user does not have to manualy
modify the code. or use the shell to get it to work, just run it, and
it works.

#You may modify the input .txt file and output location below.
coord2bearing # this command is needed to 'kickstart' the process (so
to speak). (calling it?)
#The full path and file name of the input file (original  sample csv file)
a = r"D:\D_Drive_Documents\Lund_CSV\coordinates.csv"  #the 'r'
preceeds the path so that I don't have to use '\\'
#The full path and file name of the output file (A New CSV file)
b = r"D:\D_Drive_Documents\Lund_CSV\Lund_bearings_CSVfile.csv" #the
'r' is so I don't have to use '\\'
#Run the def with its arguments
coord2bearing(a,b)


More information about the Tutor mailing list