Python Notes - Files

Contents   Installing Python   Variables   Input/Output   if   while   Functions - def   Scopes (local/global)   Function parameters   Lists (arrays)   Dictionaries   Tuples   Files   Files   Hints, tips  

A file is a collection of data stored on a disc. We 'open' a file for input (reading) or open it for output (writing). We finally close the file.

# open examples

inFile = open("C:\\temp\\test.txt", "r")  # r : reading.  NB \\ needed to get a \ on MS Windows
inFile = open("test.txt", "r")    # file assumed to be in same folder as the program
outFile = open("demo.txt", "w")   # w: writing  (can also use "a" for appending output
Note that inFile, outFile are program names for the files, not the names that the O.S knows files by.

In the following example, we create a list of names, write them to a file (one per line), then read in back in 3 ways:



names = ["pete", "Fred", "George"]

#write it to  a file
outfile = open("test.txt","w")
for name in names:
    outfile.write(name + "\n")  # one per line, with a newline at end
outfile.close()

#To Read a file all at once
infile = open("test.txt","r")
text = infile.read( )
infile.close()

# read a line at a time, append to  a new list
infile = open("test.txt","r")
newnames = []
testData = infile.readline( )
while testData != "":
    newnames.append(testData)
    testData = infile.readline( )  # but readline puts a \n at end of each string
infile.close()

# read all at once, then split into lines, placeing the result in  a list
#  this if often what we require.
infile = open("test.txt","r")
filenames = infile.read().splitlines()
infile.close()

#results:
print "Original List = ", names
print "text = ", text, "\nNOTE: just a string containing 3 lines - NOT a list"
print "newnames = ", newnames, "\n a list but with newline appended after each item - not good"
print "filenames contents = ", filenames, "\n THE CORRECT LIST"


Contents   Installing Python   Variables   Input/Output   if   while   Functions - def   Scopes (local/global)   Function parameters   Lists (arrays)   Dictionaries   Tuples   Files   Files   Hints, tips