Here’s another example (
ReadFile.py
) that reads in a file name as an
argument from the command line (run it from the shell with python3
ReadFile.py lename). The program opens the file, reads each line
as a string, and prints it. Note that print() acts like println() does
in other languages; it adds a new line to the string that is printed.
The end argument to print() suppresses the new line:
# Open and read a le from command-line argument
import sys
if (len(sys.argv) != 2):
print("Usage: python3 ReadFile.py lename")
sys.exit()
scriptname = sys.argv[0]
lename = sys.argv[1]
le = open(lename, "r")
lines = le.readlines()
le.close()
for line in lines:
print(line,end = '')
Even More Modules
One of the reasons Python is so popular is that there ...