Reading and Writing file in Python

Reading and Writing file in Python

If you did the Study Drills from the last exercise, you should have seen all sorts of commands (methods/functions) you can give to fi les. Here’s the list of commands I want you to remember:

  • close—Closes the file. Like File- >Save.. in your editor.
  • read—Reads the contents of the file. You can assign the result to a variable.
  • readline—Reads just one line of a text file.
  • truncate—Empties the file. Watch out if you care about the file.
  • write(stuff)—Writes stuff to the file.

For now, these are the important commands you need to know. Some of them take parameters, but we do not really care about that. You only need to remember that write takes a parameter of a string you want to write to the file.

1 from sys import argv
3 script, filename = argv
5 print "We're going to erase %r." % filename
6 print "If you don't want that, hit CTRL- C (^C)."
7 print "If you do want that, hit RETURN."
9 raw_input("?")
11 print "Opening the file..."
12 target = open(filename, 'w')
14 print "Truncating the file. Goodbye!"
15 target.truncate()
17 print "Now I'm going to ask you for three lines."
19 line1 = raw_input("line 1: ")
20 line2 = raw_input("line 2: ")
21 line3 = raw_input("line 3: ")
23 print "I'm going to write these to the file."
25 target.write(line1)
26 target.write("\n")
27 target.write(line2)
28 target.write("\n")
29 target.write(line3)
30 target.write("\n")
32 print "And finally, we close it."
33 target.close()


We're going to erase 'test.txt'.
 If you don't want that, hit CTRL- C (^C).
 If you do want that, hit RETURN.
 Opening the file...
 Truncating the file. Goodbye!
 Now I'm going to ask you for three lines.
 line 1: Mary had a little lamb
 line 2: It's fleece was white as snow
 line 3: It was also tasty
 I'm going to write these to the file.
 And finally, we close it.
1 from sys import argv
2 from os.path import exists
4 script, from_file, to_file = argv
6 print "Copying from %s to %s" % (from_file, to_file)
8 # we could do these two on one line too, how?
9 in_file = open(from_file)
10 indata =
12 print "The input file is %d bytes long" % len(indata)
14 print "Does the output file exist? %r" % exists(to_file)
15 print "Ready, hit RETURN to continue, CTRL- C to abort."
16 raw_input()
18 out_file = open(to_file, 'w')
19 out_file.write(indata)
21 print "Alright, all done."
23 out_file.close()
24 in_file.close()


Copying from test.txt to new_file.txt
 The input file is 21 bytes long
 Does the output file exist? False
 Ready, hit RETURN to continue, CTRL- C to abort.

Study Drills

  1. If you feel you do not understand this, go back through and use the comment trick to get it squared away in your mind. One simple English comment above each line will help you understand or at least let you know what you need to research more.
  2. Write a script similar to the last exercise that uses read and argv to read the file you just created.
  3. There’s too much repetition in this file. Use strings, formats, and escapes to print out line1, line2, and line3 with just one target.write() command instead of six.

What does ‘w’ mean?

It’s really just a string with a character in it for the kind of mode for the file. If you use ‘w’, then you’re saying “open this file in ‘write’ mode”—hence the ‘w’ character. There’s also ‘r’ for “read,” ‘a’ for append, and modifiers on these.

What are the modifiers to the file modes we can use?

The most important one to know for now is the + modifier, so you can do ‘w+’, ‘r+’, and ‘a+’. This will open the file in both read and write mode and, depending on the character used, position the file in different ways.