[Tutor] get columns from txt file

Prasad, Ramit ramit.prasad at jpmorgan.com
Wed Jul 11 16:42:41 CEST 2012


> I have a group of files in a directory.
> I want to extract from  files whose names start with  bb_   column number 5 to
> an excel file. I have 6  bb_  files, therefore I want to get 6 columns (5th
> column from each file)
> This code is working,with the following errors:
> * I get the data in only one column, instead of six
> * I get white cell after every extracted cell
> 
> I've got  help from http://mail.python.org/pipermail/tutor/2004-
> November/033474.html, though it is not working for me
> 
> This is my code:
> 
> 
> import os
> import fnmatch
> import csv
> 
> path = '//......'
> files=os.listdir(path)
> csv_out=csv.writer(open('out.csv', 'w'), delimiter='  ')
> 
> for infile in files:
> 
>         if fnmatch.fnmatch(infile, 'bb_*'):
>                 print infile
> 
>                 filename= path+infile
>                 print filename
> 
>                 f=open(filename)
>                 for line in f.readlines():
>                        b=line.split('\t')
>                        csv_out.writerow(b[5])
>                f.close

You get 6 lines because csv_out.writerow writes a row and then
goes to the next line.

What you want to do is read through each file and append each
value to a list. Once you are done reading, write the list using
the csv module.

I am not sure what you mean by "white cell after every extracted
cell" but if you mean spaces you can use (where output is a list).

output.append(b[5].strip()) 

Also, csv files should be opened using 'wb' not 'w' otherwise
you will get extra lines in the file. Maybe this is what you
meant by white cell?


Ramit


Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology
712 Main Street | Houston, TX 77002
work phone: 713 - 216 - 5423

--
This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list