Working with Files in Python

Last modified: 
Tuesday, March 31st, 2015

Creating an Empty File

open(pathtofile, 'w').close()

Writing to a File

pathtofile = 'oneline.txt'
txt = "A line of text";
thefile = open(pathtofile, 'w') # 'w' opens a file for overwriting. 
thefile.write(txt)
thefile.close()
pathtofile = 'twolines.txt'
txt = "Two lines of text.\nThe End.";
thefile = open(pathtofile, 'w')
thefile.write(txt)
thefile.close()
pathtofile = 'manylines.txt'
thefile = open(pathtofile, 'w')
thefile.write("Many lines of text,\n")
thefile.write("May be easier to deal with,\n")
thefile.write("By calling write() multiple times.\n")
thefile.close()

Append to a File

pathtofile = "manylines.txt"
thefile = open(pathtofile, 'a') # 'a' opens the file for appending.
thefile.write("\n\n")
thefile.write("But is it really the end?\n\n")
thefile.write("Yes, Howard.")
thefile.close()


The operator of this site makes no claims, promises, or guarantees of the accuracy, completeness, originality, uniqueness, or even general adequacy of the contents herein and expressly disclaims liability for errors and omissions in the contents of this website.