LPTHW Exercise 15-17: Reading and Writing Files

Learn Python the Hard Way by Zed Shaw .:

# Reading and Writing Files
# * close - closes the file
# * read - reads the contents of a file... can assign the result to a variable
# * readline - reads just one line of a text file
# * truncate - empties the file
# * write('stuff') - writes 'stuff' to the file

from sys import argv

script, filename = argv

print "We're going to erase %r." % filename
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."


print "Opening the file..."
# open 'r' (read (default)) 'w' writing and 'a' append
# 'w' will truncate the file if it already exists
target = open(filename, 'w')

print "Truncating the file. Goodbye!"
# truncate not necessary... 'w' already handles it

print "Now I'm going to ask you for three lines."

line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")

print "I'm going to write these to the file."

target.write("{0}\n{1}\n{2}\nWhat was that last bit? I said...\n" \
    "{2}\n".format(line1, line2, line3))

print "And finally, we close it."

Bonus: Last night I attended the monthly Python Toronto Meetup. It was unintelligible (for a beginner) but inspiring (to me to learn more)! :-)

More • pythonprogramming