[Tutor] Add rownumber to list of .arff files

Daan Raemdonck daan.raemdonck at telenet.be
Sun Jan 16 13:03:03 CET 2011


Thank you David!
I've incorporated your parts into my code, and after some fiddling it
worked!
I've kept the glob.glob though because having to type all filenames (as in
your code) would take me too long.

Solved problem:
Add a casenumber to every line in a directory filled with .arff files, write
back to same filename prefixed with TRE_

Code:
import os, glob

fileprefix = 'TRE_'
path = '/bla/example/'
for infile in glob.glob( os.path.join(path, '*.arff') ):
	print "current file is: " + infile
	lines= open(infile).readlines()
	(filepath, filename) = os.path.split(infile)
	outname = ('%s%s'%(fileprefix,filename)) 
	outtext = ['%d %s' % (i, line) for i, line in enumerate(lines)]
	outfile = open(outname, "w")
	outfile.writelines(outtext)
	outfile.close()

Sincerely,
Daan


-----Original Message-----
From: David Hutto [mailto:smokefloat at gmail.com] 
Sent: zaterdag 15 januari 2011 22:50
To: Daan Raemdonck
Cc: tutor at python.org
Subject: Re: [Tutor] Add rownumber to list of .arff files

>>> filename = ['file1','file2','file3']
>>> fileprefix = 'TRE_'
>>> for item in filename: print('%s%s'%(fileprefix,item))
...
TRE_file1
TRE_file2
TRE_file3

or with list comp

>>> combined = [('%s%s'%(fileprefix,item)) for item in filename]
>>> combined
['TRE_file1', 'TRE_file2', 'TRE_file3']
>>>



More information about the Tutor mailing list