Writing a File


file.writelines(wordList) file.write("\n\nFormatted text:\n") print >>file,"\t%s Color Adjust" % word

Just as with reading the contents of a file, there are several ways to write data out to a file. The easiest, yet the most dynamic and powerful, is the write(string) function. The write function writes the string argument to the file at the current file pointer. Although the write function itself is relatively simple, the power of Python with regard to string manipulation makes the capabilities of the write function virtually limitless.

Python provides the writelines(sequence) function to save time writing a list of data out to the file. The writelines function typically accepts a list of strings and writes those strings to the file.

Another option available in Python is to redirect the print statement out to a file using the >> redirection operation. This allows you to use the versatility of the Python print function to format and write data out to a file.

wordList = ["Red", "Blue", "Green"] filePath = "output.txt" #Write a list to a file file = open(filePath, 'wU') file.writelines(wordList) #Write a string to a file file.write("\n\nFormatted text:\n") #Print directly to a file for word in wordList:     print >>file,"\t%s Color Adjust" % word file.close()


write_file.py

RedBlueGreen Formatted text:        Red Color Adjust        Blue Color Adjust        Green Color Adjust


Contents of output.txt file



Python Phrasebook(c) Essential Code and Commands
Python Phrasebook
ISBN: 0672329107
EAN: 2147483647
Year: N/A
Pages: 138
Authors: Brad Dayley

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net