新手学python-笨方法学python-ex20-函数和文件

跟着笨方法学python个教程学习,边学边做习题边记录。

新手学python-笨方法学python-ex20-函数和文件 - 学习记录

课程内容:

回忆一下函数的要点,然后一边做这节练习,一边注意一下函数和文件是如何在一起协作发挥作用的。

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."

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)


特别注意一下,每次运行 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.通读脚本,在每行之前加上注解,以理解脚本里发生的事情。

2.每次 print_a_line 运行时,你都传递了一个叫 current_line 的变量。在每次调用函数时,打印出 current_line 的至,跟踪一下它在 print_a_line 中是怎样变成 line_count 的。

3.找出脚本中每一个用到函数的地方。检查 def 一行,确认参数没有用错。

4.上网研究一下 file 中的 seek 函数是做什么用的。试着运行 pydoc file 看看能不能学到更多。
 seek(...)
     seek(offset[, whence]) -> None.  Move to new file position.

     Argument offset is a byte count.  Optional argument whence defaults to
     0 (offset from start of file, offset should be >= 0); other values are 1
     (move relative to current position, positive or negative), and 2 (move
     relative to end of file, usually negative, although many platforms allow
     seeking beyond the end of a file).  If the file is opened in text mode,
     only offsets returned by tell() are legal.  Use of other offsets causes
     undefined behavior.
     Note that not all file objects are seekable.
    
5.研究一下 += 这个简写操作符的作用,写一个脚本,把这个操作符用在里边试一下。

a+=b意思就是a=a+b

>>> x = 100
>>> x += x
>>> print x
200
>>> x += 1
>>> print x
201
>>>

 


至此,笨方法学python-ex20-函数和文件这一小节的学习结束了。

Friday, November 06, 2015 | Python

文章评论

No comments posted yet.

发表评论

Please add 6 and 8 and type the answer here: