[Tutor] how to select a column from all files in one directory?

Kent Johnson kent37 at tds.net
Tue Nov 23 16:25:48 CET 2004


This will only output the data from the first line of each file in the 
source directory. If the files have multiple lines, you need another 
loop. see below.

Also you can make a string with a tab in it with '\t', maybe more 
readable than this: '	'

Kent

John Purser - Gmail wrote:
> Morning Kumar,
> 
> This worked for me:
> ###Code Start###
> import os
> path = 'C:\\Documents and Settings\\WHOEVER\\My Documents\\temp\\'
> files = os.listdir(path)
> out = file('output.txt', 'w')
> 
> for inFile in files:
> 	f = file(path + inFile, 'r')
	for line in f:
	 	b = line.split('	')	#There's a tab in there, not spaces
	 	if len(b) >= 3:
	 		out.write(b[3] + '\n')
> 	f.close()
> 
> out.close()
> 
> ###Code End###
> 
> 
> I'd give the output file an output directory of it's own to be sure I didn't
> clobber anything and of course those are windows directory seperators.
> 
> John Purser
> 
> -----Original Message-----
> From: tutor-bounces at python.org [mailto:tutor-bounces at python.org]On
> Behalf Of kumar s
> Sent: Tuesday, November 23, 2004 05:38
> To: tutor at python.org
> Subject: [Tutor] how to select a column from all files in one directory?
> 
> 
> Dear group,
>  I have ~40 tab-delimitted text files in one
> directory. I have to select 4th column from all these
> files and write it into a single tab delimitted text
> file. How can I do this in python.
> 
> I read a prev. post on tutor and tried the following:
> 
> 
>>>files = listdir('path')
> 
> 
> This returns the files(file names) in the directory as
> a list. However, I need the 4th column from all the
> files in the directory.
> 
> Can you please help me.
> 
> Thank you.
> 
> -kumar
> 
> __________________________________________________
> Do You Yahoo!?
> Tired of spam?  Yahoo! Mail has the best spam protection around
> http://mail.yahoo.com
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
> 


More information about the Tutor mailing list