多个文件对象,如何交叉打印文件和正常打印文件
正常打印:
# 示例 1: 迭代单个文件对象(逐行读取)
with open('a.file') as f:
for line in f: # 迭代文件对象,逐行读取
print(line.strip())
# 示例 2: 迭代文件对象元组
with open('a.file') as f1, open('b.file') as f2:
for file_obj in f1, f2: # 迭代元组,获取文件对象
print(f"文件信息: {file_obj}")
# 如果需要读取内容,需要再次迭代
for line in file_obj:
print(line.strip())
交叉同时打印:
# 方法 1: 使用 zip 同时迭代两个文件
with open('a.file') as f1, open('b.file') as f2:
for line1, line2 in zip(f1, f2):
print(f"文件1: {line1.strip()}")
print(f"文件2: {line2.strip()}")
# 方法 2: 使用 itertools.zip_longest 处理不同行数的文件
import itertools
with open('a.file') as f1, open('b.file') as f2:
for line1, line2 in itertools.zip_longest(f1, f2, fillvalue=""):
print(f"文件1: {line1.strip()}")
print(f"文件2: {line2.strip()}")
#方法3:使用 readlines() 读取所有行
python
with open('a.file') as f1, open('b.file') as f2:
lines1 = f1.readlines()
lines2 = f2.readlines()
# 找到最大行数
max_lines = max(len(lines1), len(lines2))
# 交叉打印
for i in range(max_lines):
if i < len(lines1):
print(lines1[i].strip())
if i < len(lines2):
print(lines2[i].strip())
#方法4:分别迭代两个文件
python
with open('a.file') as f1, open('b.file') as f2:
# 先打印第一个文件的所有行
for line in f1:
print(line.strip())
# 然后打印第二个文件的所有行
for line in f2:
print(line.strip())