parse a csv file into a text file
Dave Angel
davea at davea.name
Wed Feb 5 19:57:26 EST 2014
Zhen Zhang <zhen.zhang.uoft at gmail.com> Wrote in message:
> Hi, every one.
>
> I am a second year EE student.
> I just started learning python for my project.
>
> I intend to parse a csv file with a format like
>
> 3520005,"Toronto (Ont.)",C ,F,2503281,2481494,F,F,0.9,1040597,979330,630.1763,3972.4,1
> 2466023,"Montréal (Que.)",V ,F,1620693,1583590,T,F,2.3,787060,743204,365.1303,4438.7,2
> 5915022,"Vancouver (B.C.)",CY ,F,578041,545671,F,F,5.9,273804,253212,114.7133,5039.0,8
> 3519038,"Richmond Hill (Ont.)",T ,F,162704,132030,F,F,23.2,53028,51000,100.8917,1612.7,28
>
> into a text file like the following
>
> Toronto 2503281
> Montreal 1620693
> Vancouver 578041
>
> I am extracting the 1st and 5th column and save it into a text file.
Looks to me like columns 1 and 6.
>
> This is what i have so far.
>
>
> [code]
>
> import csv
> file = open('raw.csv')
> reader = csv.reader(file)
>
> f = open('NicelyDone.text','w')
>
> for line in reader:
> f.write("%s %s"%line[1],%line[5])
Why not use print to file f? The approach for redirection is
different between python 2 and 3, and you neglected to say which
you're using.
>
>
> My thinking is that I could add those 2 string together like c=a+' ' +b, that would give me the format i wanted.
And don't forget the "\n" at end of line.
> So i can use f.write() to write into a file ;)
Or use print, which defaults to adding in a newline.
> Sorry if my questions sounds too easy or stupid.
>
Not in the least.
>
>
--
DaveA
More information about the Python-list
mailing list