Thursday, April 5, 2012

Python Snippet, Writing Text To A File

Let's say you have a program that runs a long process, and you want to write information to a text file. Using the file IO functions, you can easily do this:

data = ["a","b","c","d"]
myFile = open("info.dat", 'w',0)
for item in data:
    myFile.write("%s\n" % item)
myFile.flush()
myFile.close()
del myFile
del data


Now you have a text file where each item in the list is on a new line.

Enjoy

2 comments:

Anonymous said...

A cleaner more pythonic way starting at 2.6 is to use a with statement. No need to worry about flushing or closing the file.

data = ["a", "b", "c", "d"]
with open("info.dat", 'w', 0) as myFile:
for item in data:
myFile.write("{0}\n".format(item))

Stefan O. said...

Writing information to a file while a long process is running reminds me of the "logging" module. It supports the automatic addition of the timestamp when a message is being written and other nice formatting options, which often come in place while writing process information to files:

http://docs.python.org/howto/logging.html#logging-basic-tutorial

import logging
logging.basicConfig(filename='example.log',level=logging.DEBUG)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')