《笨办法学Python3》练习二十:函数和文件

练习代码

from sys import argv

script, input_file = argv

# 用函数封装文件基本操作
def print_all(f):
    print(f.read())

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print(line_count, f.readline())

current_file = open(input_file)

print("First let's print the whole file:\n")

print_all(current_file)

print("Now let's rewind, kind of like a tape.")

# back to the first line
rewind(current_file)

print("Let's print three lines:")

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

Study Drills

  1. Write an English comment for each line to understand what that line does.
# import argv from sys module
from sys import argv

# unpack
script, input_file = argv

# define functions
def print_all(f):
    print(f.read())

def rewind(f):
    f.seek(0)

def print_a_line(line_count, f):
    print(line_count, f.readline())

current_file = open(input_file)

print("First let's print the whole file:\n")

print_all(current_file)

print("Now let's rewind, kind of like a tape.")

# back to the first line
rewind(current_file)

print("Let's print three lines:")

current_line = 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)

current_line = current_line + 1
print_a_line(current_line, current_file)
  1. Each time print_a_line is run, you are passing in a variable, current_line. Write out
    what current_line is equal to on each function call, and trace how it becomes line_count
    in print_a_line.

  2. Find each place a function is used, and check its def to make sure that you are giving it the right arguments.

  3. Research online what the seek function for file does. Try pydoc file, and see if you can
    figure it out from there. Then try pydoc file.seek to see what seek does.

seek()函数共有两个参数seek(offset, from_what)offset是必填参数,指从from_what开始的偏移量(以byte为单位),from_what是可选参数,共有012三个值可选,0代表文件开始位置,1代表当前位置, 2代表文件最末位置,不显式声明时默认为0

所以seek(0)等价于seek(0, 0)

  1. Research the shorthand notation +=, and rewrite the script to use += instead.

current_line = current_line + 1 等价于 current_line += 1

补充

  1. readline是以\n来识别一行的。

你可能感兴趣的:(《笨办法学Python3》练习二十:函数和文件)