python-hard-way/3exercises/ex20.py

37 lines
1.3 KiB
Python
Raw Normal View History

2019-03-12 02:02:10 +00:00
# Import the argv tool from system tools.
2019-03-04 03:42:45 +00:00
from sys import argv
2019-03-12 02:02:10 +00:00
# Grab some command line arguments with argv.
2019-03-04 03:42:45 +00:00
script, input_file = argv
2019-03-12 02:02:10 +00:00
def print_all(f): # Define a function with one argument.
print(f.read()) # Read an a file passed to this function.
2019-03-04 03:42:45 +00:00
2019-03-12 02:02:10 +00:00
def rewind(f): # Define a function with one argument.
f.seek(0) # Start from the first line.
2019-03-04 03:42:45 +00:00
2019-03-12 02:02:10 +00:00
def print_a_line(line_count, f): # Define a function with two arguments.
print(line_count, f.readline()) # Print the line.
2019-03-04 03:42:45 +00:00
2019-03-12 02:02:10 +00:00
current_file = open(input_file) # Open the file input_file as "current_file"
2019-03-04 03:42:45 +00:00
2019-03-12 02:02:10 +00:00
print("First let's print the whole file:\n") # Tell the user we're printing the whole file.
2019-03-04 03:42:45 +00:00
2019-03-12 02:02:10 +00:00
print_all(current_file) # Print the whole file.
2019-03-04 03:42:45 +00:00
2019-03-12 02:02:10 +00:00
print("Now let's rewind, kind of like a tape.") # Tell the user we're starting over.
2019-03-04 03:42:45 +00:00
2019-03-12 02:02:10 +00:00
rewind(current_file) # Print the first line.
2019-03-04 03:42:45 +00:00
2019-03-12 02:02:10 +00:00
print("Let's print three lines:") # Tell the user we're printing three lines.
2019-03-04 03:42:45 +00:00
2019-03-12 02:02:10 +00:00
current_line = 1 # Set the current line to the second line.
print_a_line(current_line, current_file) # Print the current line.
2019-03-04 03:42:45 +00:00
2019-03-12 02:02:10 +00:00
current_line = current_line + 1 # Increment the current line by one, making it the third line.
print_a_line(current_line, current_file) # Print the current line.
current_line = current_line + 1 # Increment the current line by one, making it the fourth line.
print_a_line(current_line, current_file) # Print the current line.