《笨办法学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来识别一行的。
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 12,129评论 0 10
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 13,394评论 0 23
  • 无法预测未来 一直如履薄冰 人生就是一场赌博 对手就是自己
    z超哥阅读 50评论 0 0
  • 不经历风雨,怎么见彩虹
    初见LYC阅读 1,001评论 0 0
  • 不若寻出一片虚无的景 将你的颜色泼洒上去 那是水墨不及的黑色
    伍丁零阅读 884评论 1 6