Reading File in Python
Everything you’ve learned about raw_input and argv is so you can start reading files. You may have to play with this exercise the most to understand what’s going on, so do it carefully and remember your checks. Working with files is an easy way to erase your work if you are not careful.
1 from sys import argv
2
3 script, filename = argv
4
5 txt = open(filename)
6
7 print "Here's your file %r:" % filename
8 print txt.read()
9
10 print "Type the filename again:"
11 file_again = raw_input("> ")
12
13 txt_again = open(file_again)
14
15 print txt_again.read()
Output
Here's your file 'ex15_sample.txt':
This is stuff I typed into a file.
It is really cool stuff.
Lots and lots of fun to have in here.
Lines 1–3 should be a familiar use of argv to get a fi lename. Next we have line 5 where we use a new command open. Right now, run pydoc open and read the instructions. Notice how like your own scripts and raw_input, it takes a parameter and returns a value you can set to your own variable. You just opened a file.
Study Drills
- Above each line, write out in English what that line does.
- If you are not sure, ask someone for help or search online. Many times searching for “python THING” will find answers for what that THING does in Python. Try searching for “python open.”
- I used the name “commands” here, but they are also called “functions” and “methods.” Search around online to see what other people do to define these. Do not worry if they confuse you. It’s normal for programmers to confuse you with vast extensive knowledge.
- Get rid of the part from lines 10– 15 where you use raw_input and try the script then.
- Use only raw_input and try the script that way. Think of why one way of getting the filename would be better than another.
Does txt = open(filename) return the contents of the fi le?
No, it doesn’t. It actually makes something called a “file object.” You can think of it like an old tape drive that you saw on mainframe computers in the 1950s or even like a DVD player from today. You can move around inside them, and then “read” them, but the file is not the contents.
What does from sys import argv mean?
For now, just understand that sys is a package, and this phrase just says to get the argv feature from that package. You’ll learn more about these later.
Why is there no error when we open the file twice?
Python will not restrict you from opening a file more than once, and in fact sometimes this is necessary.