【问题标题】:python3: read two text files and print each file in vertical split so easy to log for comparingpython3:读取两个文本文件并在垂直拆分中打印每个文件,以便于记录比较
【发布时间】: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


【解决方案1】:

有可能

separator = " "
file1 = open("f1")
file2 = open("f2") 
con1 = file1.readlines()
con2 = file2.readlines()
file1.close()
file2.close()
max_length = max(len(con1), len(con2))
for i in range(max_length):
    print(con1[i].rstrip() + separator + con2[i].rstrip() + "\n")

【讨论】:

  • 谢谢,但问题是所有的行都混淆了我如何格式化看起来像一个表格。
  • 它不会打印更多行,例如如果 file2 有更多行
  • 我编辑了答案。它现在使用较长文件的长度来循环槽。
猜你喜欢
  • 1970-01-01
  • 2012-02-18
  • 1970-01-01
  • 1970-01-01
  • 2020-12-13
  • 2020-04-16
  • 1970-01-01
  • 2020-12-29
  • 1970-01-01
相关资源
最近更新 更多