1.File.readline() 方法用于从文件读取整行,每次读取一行,如此循环,包括 “\n” 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 “\n” 字符。
readline解析
read/readline/readlines详解
2.File.seek()方法用于移动文件读取指针到指定位置 seek方法
ex20_sample.txt内容如下
To all the people out there.
I say I don’t like my hair.
I need to shave it off.
脚本内容
from sys import argv
scripts,input_file = argv #这里的input_file为ex20_sample.txt,一共三行内容
current_file = open(input_file) #把input_file打开,返回一个文件对象给current_file
current_line = 1 #定义当前行为1
def print_all(f): #一个参数f,函数print_all可以将参数f的内容read后输出
print(f.read())
def rewind(f): #一个参数f,函数rewind可以将参数f的内容
f.seek(0) #将指针移动到最开始的位置,也即0
def print_a_line(line_count,f): #两个参数line_count和f,第一个参数直接输出,第二个参数使用readline进行输出
print(line_count,f.readline())
print("First let's print the whole file:")
print_all(current_file) #将current_file作为函数print_all的参数
print("And let's rewind,kind of like a tape")
rewind(current_file)
print("Let's print three lines:")
print_a_line(current_line,current_file) #首先输出当前行,然后是文件第一行的内容
current_line = current_line + 1 #行数+1
print_a_line(current_line,current_file) #因为readline是每行循环读取的,这时的输出文件第二行的内容
current_line = current_line + 1
print_a_line(current_line,current_file)
运行结果
PS E:\tonyc\Documents\Vs workspace\The Hard Way> python ‘.\ex20(函数和文件).py’ .\ex20_sample.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.
And 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.
如果去掉seek()的定位过程,也即注释掉rewind(current_file),运行结果如下,可以看到这时只有行数的显示,行内容并没有输出,因为之前执行了print_all函数,里面的read()默认是指针从文件头部到尾部,执行之后指针指向文件尾部,此时内容为空,所以要使用seek(0)重新定位至头部
PS E:\tonyc\Documents\Vs workspace\The Hard Way> python ‘.\ex20(函数和文件).py’ .\ex20_sample.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.
And let’s rewind,kind of like a tape
Let’s print three lines:
1
2
3
总结
- 可以使用current_line += 1来简写