为了账号安全,请及时绑定邮箱和手机立即绑定

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

标签:
Python

# -- 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


点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消