File Contents:
Think of a file as a very long string of characters, with some non-printable
characters embedded in it (principally: newline characters). For instance,
if you typed the following 3 lines into the file Fred.txt (using, say,
GEDIT, not Microsoft Word)...
abc d ef |
There would be 9 characters actually stored in the file:
abc\nd\nef\n
where the '\n' is actually a single character called the "newline" character.
Reading a file:
First, we need to "open the file for reading". The
file must already be there to be read -- if it isn't, then Python cannot open
and read it, and an error will result.
f = open('Fred.txt','r') # open it for reading s = f.read() # read entire contents into a string variable f.close() # you MUST close the file afterwards print 'Here are the contents of "Fred.txt":' print s |
Try this in the Python shell....
Writing to a file:
If you open a file for writing, then that file will be automatically
created (if it didn't exist), or if it did exist, then it will be overwritten
with the new information that you're about to write (in other words, all old
information in the file will be erased first).
bleep = open('Harry.txt','w') # open it for writing bleep.write('first line\n') # write a line bleep.write('second line\nthird line\n') # write another 2 lines bleep.close() # you MUST close the file when finished |
Try this in the Python shell, and then open the Harry.txt file using GEDIT to see what you've written.
Processing files:
Counting lines in Fred.txt using f.read() |
f = open('Fred.txt','r') s = f.read() lines = s.split('\n') # creates array of lines, recognizing newlines as line separators print 'There are '+str(len(lines))+' lines in Fred.txt' f.close() |
Counting lines in Fred.txt using f.readlines() |
f = open('Fred.txt','r') slines = f.readlines() # creates an array of lines print "There are '+str(len(slines))+' in Fred.txt' f.close() |
Capitalizing the words in Fred.txt and writing them into George.txt |
incoming = open('Fred.txt','r') slines = incoming.readlines() incoming.close() outgoing = open('George.txt','w') for each_line in slines: words = each_line.split() # creates an array of words from the current line's string cap_words = [] # new array with capitalized words for each_word in words: cap_words.append(each_word.capitalize()) # yes, there is such a method whole_line = ' '.join(cap_words) # re-join array of words back into a string of words with a space between each word outgoing.write(whole_line + '\n') # remember to add the newline to the end of each line outgoing.close() |