企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 习题 20: 函数和文件 回忆一下函数的要点,然后一边做这节练习,一边注意一下函数和文件是如何在一起协作发挥作用的。 <table class="highlighttable"><tbody><tr><td class="linenos"> <div class="linenodiv"> <pre> 1&#13; 2&#13; 3&#13; 4&#13; 5&#13; 6&#13; 7&#13; 8&#13; 9&#13; 10&#13; 11&#13; 12&#13; 13&#13; 14&#13; 15&#13; 16&#13; 17&#13; 18&#13; 19&#13; 20&#13; 21&#13; 22&#13; 23&#13; 24&#13; 25&#13; 26&#13; 27&#13; 28&#13; 29&#13; 30&#13; 31&#13; 32&#13; 33</pre> </div> </td> <td class="code"> <div class="highlight"> <pre>from sys import argv&#13; &#13; script, input_file = argv&#13; &#13; def print_all(f):&#13; print f.read()&#13; &#13; def rewind(f):&#13; f.seek(0)&#13; &#13; def print_a_line(line_count, f):&#13; print line_count, f.readline()&#13; &#13; current_file = open(input_file)&#13; &#13; print "First let's print the whole file:\n"&#13; &#13; print_all(current_file)&#13; &#13; print "Now let's rewind, kind of like a tape."&#13; &#13; rewind(current_file)&#13; &#13; print "Let's print three lines:"&#13; &#13; current_line = 1&#13; print_a_line(current_line, current_file)&#13; &#13; current_line = current_line + 1&#13; print_a_line(current_line, current_file)&#13; &#13; current_line = current_line + 1&#13; print_a_line(current_line, current_file)&#13; </pre> </div> </td> </tr></tbody></table> 特别注意一下,每次运行 print_a_line 时,我们是怎样传递当前的行号信息的。 ### 你应该看到的结果 ~~~ $ python ex20.py test.txt First let's print the whole file: To all the people out there. I say I don't like my hair. I need to shave it off. Now let's rewind, kind of like a tape. Let's print three lines: 1 To all the people out there. 2 I say I don't like my hair. 3 I need to shave it off. $ ~~~ ### 加分习题 1. 通读脚本,在每行之前加上注解,以理解脚本里发生的事情。 1. 每次 print_a_line 运行时,你都传递了一个叫 current_line 的变量。在每次调用函数时,打印出 current_line 的至,跟踪一下它在 print_a_line 中是怎样变成 line_count 的。 1. 找出脚本中每一个用到函数的地方。检查 def 一行,确认参数没有用错。 1. 上网研究一下 file 中的 seek 函数是做什么用的。试着运行 pydocfile 看看能不能学到更多。 1. 研究一下 += 这个简写操作符的作用,写一个脚本,把这个操作符用在里边试一下。