Hello, some of you may have read my first post...if you did I tired Python and love. It just so fast to program in compared to Java or VB (my 'mother tongue').
I am have bit of trouble with syntax...I think. I have almost managed to import a .cvs (in other words a text file) into the application and got part way to splitting it into a 2D array. Here is the code I have so far
print "Welcome To UNIT 6"
print "-----------------"
# Creates file object
file = open("C:\\Documents and Settings\Peter Sutton\Desktop\Practice Open Book Graphs.txt")
# Declare arrays
cell = []
array = []
# Reads each line from the file or each row from the spread sheet
for line in file:temp = line.replace("\n","") # Removes the new line marker
while temp != "":print array # Prints the array for testingcell = temp.partition(",") # Splits the row read from the file into cells
if cell [1] != "":array.append(cell[0]) # Adds the cells to the array if cells to addelse:
temp = cell [2]temp = "" # Breaks while loop
The problem with this code is that it does not create an array that reflects the spread sheet. It stick the data in each cell into the array after the last.
I need to know how to make a proper 2D array and how to decide where the data from the .cvs file goes in the array.
I have supplied my test data so you can try my code. (Its my practice open book stuff for chemistry AS level)
Last edited by annannienann; 04-23-2007 at 09:18 AM.
Hi annannienann,
For CSV's I would take a good look at the csv module documentation, but, looking at your txt file input you should be able to use the .split() string method to split the input on commas, and, because this returns a list of strings, you could use a list of lists as a 2D array something like the following (untested):
- Paddy.Code:txtfile = ... data = [] for line in txtfile: data.append( line.rstrip().split(',') )
P.S. It is not good to re-assign file - it is a Python built-in function. (Thats why I have used txtfile).
Python actually has a csv module. Read the Python manual on it, and it will make your life much easier!
Thanks everyone. Cracked it..
import csv
reader = csv.reader(open("C:\\Documents and Settings\Peter Sutton\Desktop\Practice Open Book Graphs.txt", "rb"))
array = []
for row in reader:
array.append( row )
print array
There are currently 1 users browsing this thread. (0 members and 1 guests)
Bookmarks