【发布时间】:2020-05-06 15:39:50
【问题描述】:
我在想是否有可能在 python3 中实现以下目标
我有两个文本文件
文件 1
===========================================================================
0100 - Request Message RSC Transaction ID :N80L2G
===========================================================================
DE-000 004 0100
DE-002 16 0078700081608
文件 2
===========================================================================
0100 - Request Message RSC Transaction ID :N80L2L
===========================================================================
DE-000 004 0100
DE-002 16 000006776609
我想读取文件并打印或创建一个新文件,如 html 垂直页面拆分,在列文件 1 内容和下一个文件 2 内容中。
这是可以实现的,任何想法
我找到了这个,但这里的问题是它没有打印所有文件,即如果一个文件 它没有迭代的行数更多,例如,如果 file2 有更多行,它会在 file1 行结束处停止
with open(file1) as f1:
with open(file2) as f2:
for x, y in zip(f1, f2):
# print("{0}\t{1}".format(x.strip(), y.strip()))
print('{:<100} {}'.format(x.strip(), y.strip()))
解决方案
def file_len(fname):
with open(fname) as f:
for i, l in enumerate(f):
pass
return i + 1
if file_len(file1) >= file_len(file2):
with open(file1,'r') as f1,open(file2,'r') as f2:
for i in f1.readlines():
print('{:<100} {}'.format(i.rstrip(),f2.readline().rstrip()))
else:
with open(file1,'r') as f1,open(file2,'r') as f2:
for i in f2.readlines():
print('{:<100} {}'.format(f1.readline().rstrip(), i.rstrip()))
【问题讨论】:
-
你想如何分隔文件内容?按字符数、html标签等。
标签: python-3.x