python中文件内容的读写

python中文件读写是常见的操作,常用的文件打开方式是下面这种:

1
2
3
with open(file_path,'r+') as f:
for line in f:
# your code here

如果要同时打开2个或多个文件,以同时对里面的内容操作,可以采用:

1
2
3
4
5
6
7
with open(file1_path,'r+') as f1:
with open(file2_path,'r+') as f2:
with open(file3_path,'r+') as f3:
for line_f1 in f1:
line_f2=f2.readline()
line_f3=f3.readline()
# your code here

而读取文件内容也有若干种方式,除了上面的for line in f: 之外,还有:

1
2
3
4
f.readline()        # 读取文件的第一行
f.readline(index) # 读取文件的第index行
f.readlines() # 读取文件的所有行,并返回list
for i, line in enumerate(input): # loop读取文件的每一行,并返回内容和index

或者

1
2
3
4
5
6
7
examples = []
with open(src_path) as src_file, open(trg_path) as trg_file:
for src_line, trg_line in zip(src_file, trg_file):
src_line, trg_line = src_line.strip(), trg_line.strip()
if src_line != '' and trg_line != '':
examples.append(data.Example.fromlist(
[src_line, trg_line], fields))

END