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)
del myFile
del data

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



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:

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:

import logging
logging.debug('This message should go to the log file')'So should this')
logging.warning('And this, too')