-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathex15.py
27 lines (21 loc) · 913 Bytes
/
ex15.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# Exercise 15: Reading Files
# http://learnpythonthehardway.org/book/ex15.html
# loads sys and argv modules
from sys import argv
# unpacks command arguments into variables
script, filename = argv
# opens file and assigned it to variable
txt = open(filename)
# print type(txt) would return 'file'
# displayes filename (given as command argument)...
print "Here's your file %r:" % filename
print txt.read() # ...and file contents after calling read function on file variable
# let user confirm filename; open and display again
print "Type the filename again:"
file_again = raw_input("> ")
txt_again = open(file_again)
print txt_again.read()
# brain teaser: enter ex15.py when prompted for filename again => code of this file will be displayed, because it is read just like any other text file.
# Study Drill 7: properly close files by calling close() method on file variable
txt_again.close()
txt.close()