[Tutor] Fwd: arrangement of datafile
Steven D'Aprano
steve at pearwood.info
Sun Jan 5 23:44:18 CET 2014
Hi Amrita,
On Sun, Jan 05, 2014 at 10:01:16AM +0800, Amrita Kumari wrote:
> I have saved my data in csv format now it is looking like this:
If you have a file in CSV format, you should use the csv module to read
the file.
http://docs.python.org/3/library/csv.html
If you're still using Python 2.x, you can read this instead:
http://docs.python.org/2/library/csv.html
I think that something like this should work for you:
import csv
with open('/path/to/your/file.csv') as f:
reader = csv.reader(f)
for row in reader:
print(row)
Of course, you can process the rows, not just print them. Each row will
be a list of strings. For example, you show the first row as this:
> 2,ALA,C=178.255,CA=53.263,CB=18.411,,,,,,,,,,
so the above code should print this for the first row:
['2', 'ALA', 'C=178.255', 'CA=53.263', 'CB=18.411', '', '', '',
'', '', '', '', '', '']
You can process each field as needed. For example, to convert the
first field from a string to an int:
row[0] = int(row[0])
To split the third item 'C=178.255' into a key ('C') and a numeric
value:
key, value = row[2].split('=', 1)
value = float(value.strip())
Now you know how to read CSV files. What do you want to do with the data
in the file?
--
Steven
More information about the Tutor
mailing list