《艰难的方式学Python》第20练习帮助

0 投票
2 回答
1800 浏览
提问于 2025-04-16 13:11

在练习20的额外部分,我被要求对每一行代码的作用进行注释。我觉得“seek”这个部分有点让人困惑。如果有人愿意看看我对源代码的注释,帮我确认一下我是否理解正确,那就太好了。我可以不做这部分,但我觉得理解它很重要。

谢谢!

from sys import argv #imports argv from sys moduel 

script, input_file = argv #unpacks the startup arguments to script and input_file variables

def print_all(f): #defines a function that uses the read() function on whatever is in the parameter(current_file in this case)
    print f.read()

def rewind(f): #not a clue what this does really...moves to byte 0 of the file??
    f.seek(0)

def print_a_line(line_count, f): #sets a function that reads a line from the current_file
    print line_count, f.readline()

current_file = open(input_file)

print 'first of all, lets read the wole file:\n'

print_all(current_file)

print 'now lets rewind, kind of like a tape'
rewind(current_file)

print 'lets print 3 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)

2 个回答

2

file.seek 是一个可以让你回到文件开头的命令。如果没有这个命令,你只能从头到尾读一次文件,不能再回去读了。

3

是的,它将文件的当前位置设置为第一个字节。你可以在file.seek的文档中看到这一点:

file.seek(offset[, whence])

这个方法设置文件的当前读取位置,类似于标准输入输出中的fseek()。其中的whence参数是可选的,默认值是os.SEEK_SET或0(表示从文件开头开始定位);其他值包括os.SEEK_CUR或1(表示从当前位置开始定位)和os.SEEK_END或2(表示从文件末尾开始定位)。这个方法没有返回值。

注意,由于你没有为whence参数提供值,所以使用了默认值os.SEEK_SET。这意味着是绝对定位文件的位置,也就是从文件的开头开始。

撰写回答