迭代文件内容

简介

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#coding:utf-8

def process(sting):
print('Processing:',sting)

with open('somefile.txt') as f:
char = f.read(1)
while char:
process(char)
char = f.read(1)

with open('somefile.txt') as f: # 改进后去重,优美.
while True:
char = f.read(1)
if not char:
break
process(char)

with open('somefile.txt')as f:
while True:
line = f.readline() # 这里的line其实是智能的,可以识别换行符和空的区别。
if not line: # 有东西,包括换行符,就循环。
break
process(line)

with open('somefile.txt')as f:
for char in f.read():
process(char)

print('~~~~~~~~~~')

with open('somefile.txt')as f:
for line in f.readlines():
process(line)

import fileinput
for line in fileinput.input('somefile.txt'): # 这里只需要提供函数名就行了,fileinput会自己打开、读取。
process(line)