Simple file writing techiques ...

cdecarlo cdecarlo at gmail.com
Wed Jul 19 07:14:12 EDT 2006


Hello,

I've often found that I am writing little scripts at the interpretor to
read a text file, perform some conversion, and then write the converted
data back out to a file. I normally accomplish the above task by
reading the lines of the entire file into a list, preforming some
function to that list and then writing the list back out. I want to
write a generic function/module that will free me from repeatedly
typing the same thing, perhaps convertFile(filename, covertFunc) and I
was wondering what would be a more optimal solution for writing the
data,

fout = open('somefile','w')
for line in convertedData:
  fout.write("%s\n" % line)
fout.close()

 -- or --

fout = open('somefile','w')
fout.write("%s" % '\n'.join(convertedData))
fout.close()

... or maybe some hybrid of the two which writes chunks of the
convertedData list out in one shot ...

An issue that I'm probably most concerned with is scalabitiy, what if
the file was huge, like some sort of log file. As well, I know from
'import this' that there should only be one obvious way to do something
... however to me it's not so obvious :(

Any suggestions,

Colin




More information about the Python-list mailing list