Reading Files
#!/usr/bin/python3
# Print the contents of the files listed on the command line.
import sys
for fn in sys.argv[1:]:
try:
fin = open(fn, 'r')
except:
(type, detail) = sys.exc_info()[:2]
print("\n*** %s: %s: %s ***" % (fn, type, detail))
continue
print("\n*** Contents of", fn, "***")
# Print the file, with line numbers.
lno = 1
while 1:
line = fin.readline()
if not line: break;
print('%3d: %-s' % (lno, line[:-1]))
lno = lno + 1
fin.close()
print()
This program simply takes a list of files on the command line,
and lists the contents of each, with lines numbered.
There are a couple of new things from sys used here.
- sys.argv
-
This gives the list of command line arguments. The first one
(position zero) is the name of the script, as in C.
- sys.exc_info
-
This returns a list of information about the current exception.
The first item is the name of the exception, the second is
the detail information, and the third is the call stack trace-back.