[Tutor] Extracting columns from many files to different files

susana moreno colomer susana_87 at hotmail.com
Mon Jul 16 16:58:38 CEST 2012


Hi!
I have a folder, with the following text files with columns:
 
bb_ 1
bb_2
ww_1
ww_2
ff_1
ff_2
 
What I want to do is:

Extract columns 5,6, 8 from files bb_
Extract columns 3,4 from files ww_
Get 5 files, corresponding to different columns:
Files (excel files): 'ro' with colums number 5,  'bf' with colums number 6,  'sm' with column 8,  'se' with columns number 3 and  'dse' with columns number 4
 
I was following the example from: http://mail.python.org/pipermail/tutor/2009-February/067391.html 
 
import os
import fnmatch
import csv
 
path = '//(my path)/'
files=os.listdir(path)
csv_out=csv.writer(open('out1.csv', 'wb'),delimiter=' ')
 
ro=[]; bf=[]; sm=[]; se=[]; dse=[]

listofcolumns=[]
 
def column(tofile):

for infile in files:
filename= os.path.join(path,infile)
f=open(filename, 'r')
  
for line in f.readlines():
b=line.split('\t')

if fnmatch.fnmatch(filename, 'bb_*'):
A=[]; B=[]; C=[]; 
for b in line:
A.append(b[5].strip())
B.append(b[6].strip())
C.append(b[8].strip())
ro.append(A)
bf.append(B)
sm.append(C)
elif fnmatch.fnmatch(filename, 'ww_*'):
D=[]; E=[]
for b in line:
D.append(b[3])
E.append(b[4])
    
se.append(D)
dse.append(E)
f.close() 
#list of pairs of (value list, name)
listofcolumns=[(ro, 'ro'),(bf, 'bf'),(sm, 'sm'),(se, 'se'),(dse,'dse')]  
  
 for values, name in listofcolumns: 
   
output=open(name + '.csv', 'w')
   for value in values:    
     csv_out.writerows(rows)
     csv_out.writerows('\n')
  
 column(listofcolumns)
 
It does't give me any error but gives me the documents in blank
Another question, Is there anyway to write the code properly ? I am sorry about the spaces, I can send a text file 
Many thanks! :D
  		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20120716/c2948865/attachment.html>


More information about the Tutor mailing list