Computer Science
15-110, Spring 2011
Class Notes: File IO
# File Input/Output in Python
import os
def getDesktopPath(filename = ""):
# next line is odd, but works in Windows/Mac/Linux
homepath = os.getenv('USERPROFILE') or os.getenv('HOME')
return homepath + os.sep + "Desktop" + os.sep + filename
def fileExists(filename):
return os.path.exists(filename)
def deleteFile(filename):
if (fileExists(filename) == True):
os.remove(filename)
def readTextFile(filename):
if (fileExists(filename) == False):
print "File does not exist:", filename
return None
fileHandler = open(filename, "rt")
text = fileHandler.read()
fileHandler.close()
return text
def readTextFileAsList(filename):
# readlines includes '\n' characters, so we'll use split() instead
text = readTextFile(filename)
if (text == None):
return None
return text.split("\n")
def writeTextFile(text, filename):
fileHandler = open(filename, "wt")
fileHandler.write(text)
fileHandler.close()
def testFileIO():
print "Testing File IO..."
filename = getDesktopPath("test.txt")
deleteFile(filename)
assert(fileExists(filename) == False)
print "Reading from a non-existent file (error message expected)..."
text = readTextFile(filename)
assert(text == None)
text = "This is a test.\nIt is only a test."
writeTextFile(text, filename)
assert(fileExists(filename) == True)
text = readTextFile(filename)
assert(text == "This is a test.\nIt is only a test.")
textList = readTextFileAsList(filename)
assert(textList == ["This is a test.", "It is only a test."])
assert(fileExists(filename) == True)
#deleteFile(filename)
#assert(fileExists(filename) == False)
print "Passed!"
testFileIO()