码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习20:利用函数来打印文件内容

时间:2018-02-26 11:15:18      阅读:209      评论:0      收藏:0      [点我收藏+]

标签: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.

利用 += 来改变变量的值。

a = 1
print a
a += 1
print a
a += 2
print a

得到的结果如下:

PS C:\python> python No20plus.py
1
2
4

Python学习20:利用函数来打印文件内容

标签:Python   函数   

原文地址:http://blog.51cto.com/6150141/2072958

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!