继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

[Python学习] 利用函数来打印文件内容

慕工程3455409
关注TA
已关注
手记 318
粉丝 77
获赞 293

# -- coding: utf-8 --

# 从sys模块导入argv函数

from sys import argv


# 利用argv函数,把 argv 中的东西解包,将所有的参数依次赋予左边的变量名

script, input_file = argv


# 自定义一个函数,读取f的内容

def print_all(f):

    print f.read()


# 自定义函数,使用file中的seek方法来移动文件游标,用于依次读取文件行的功能

def rewind(f):

    f.seek(0)


# 该脚本的主函数,用于打印文件每一行的内容

def print_a_line(line_count, f):

    print "No.", line_count, f.readline()


# 使用file中的open方法来打开文件

current_file = open(input_file)


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


# 使用自定义的函数print_all来读取打开的文件内容

print_all(current_file)


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


# 使用上面自定义的函数rewind

rewind(current_file)


print "Let's print three lines:"


# 定义一个变量,每打印完一行就加1,把这个变量作为print_a_line函数的参数,调用print_a_line函数可以依次打印每一行。

# 下面的几行代码可以采用循环来写,以减少代码长度。

current_line = 1

print "Now Current line is : %d" % current_line

print_a_line(current_line, current_file)


current_line = current_line + 1

print "Now Current line is : %d" % current_line

print_a_line(current_line, current_file)


current_line = current_line + 1

print "Now Current line is : %d" % current_line

print_a_line(current_line, current_file)



使用python的帮助来查询seek方法的内容

python -m 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 (moverelative to end of file, usually negative, although many platforms allowseeking 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.
参数偏移是一个字节数。
可选参数从默认值为0(从文件开始时偏移,偏移量应该是大于0);
其他值:
1(表示移动相对于当前位置,正或负)
2(表示移动到文件末尾,通常是负的,尽管许多平台允许在文件的末尾进行搜索)。
如果文件是在文本模式下打开的,那么由tell()函数返回的偏移量是合法的。
使用其他偏移量会导致未定义的行为。
注意,并不是所有的文件对象都是可看到的。    
利用 += 来改变变量的值。

a = 1

print a

a += 1

print a

a += 2

print a

得到的结果如下:

PS C:\python> python No20plus.py

1

2

4


打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP