如何在python中并排打印文本文件?

如何在python中并排打印文本文件?,python,printing,Python,Printing,我编辑了“如何在python中并排打印循环?” 我试图找出如何在我的程序中并排打印 我想做的是逐行读取每个文件,并在最终打印时并排打印 我的程序有两个问题 首先,文本文件的显示方式与我预期的不同 The original 'num.text': My expectation: The result I got: 0000 1111 1 0000

我编辑了“如何在python中并排打印循环?”

我试图找出如何在我的程序中并排打印

我想做的是逐行读取每个文件,并在最终打印时并排打印

我的程序有两个问题

首先,文本文件的显示方式与我预期的不同

The original 'num.text':         My expectation:       The result I got:

0000                             1111                      1
0000                             1111                      1
2222                             2222                      2222
2222                             2222                      2222
其次,我不知道如何将程序更改为并排打印(result1和result2)。我尝试了“main def():print(result1+result2)”,但没有显示任何内容

 num.txt     num2.txt      ->  Print should be:
 0000        2222              1111  2222
 0000        2222              1111  2222
 2222        0000              2222  3333
 2222        0000              2222  3333
这是我的节目。现在真是一团糟

def file1():

    f=open("num.txt", "r")

    for line in f:
        for i in range(len(f)):
            l_line = str(f).strip("[]") 
            result1 = (l_line.replace('0','1'))
        print(result1)
file1()

def file2():

    f=open("num2.txt", "r")   
    for line in f:
        for i in range(len(f)):
            data_line = str(f).strip("[]") 
            result2 = (data_line.replace('0','3'))
        print(result2)
file2()
那么,有人能帮我解决这些问题吗? 如果你能尽可能地解释,我会很高兴的


无论如何,感谢您在下面提供的所有注释和代码。

您的代码存在许多问题

当你应该使用i时,你正在使用f,因为

f=open("textfile1.txt","r")
for i in f:    
    i = list(i)
接下来,您不断地用整个字符串f覆盖a。这是给定的

f = '123456'
list(f)

>>> ['1', '2', '3', '4', '5', '6']
对于f的长度,您不断地将a重做为整个
列表(f)
。应该是

a = list(f.rstrip("\n"))
然后,您需要在f上的循环之前创建空列表a,并附加f的每一行

f=open("textfile1.txt","r")

a = []
for i in f:    
    a.append(list(i.rstrip("\n")))
请注意,当您完成f时,应该关闭它,而不是让python在最后清理时关闭它。养成好习惯总是好的,即使是在一个小例子中,坏习惯不会伤害到你

定义完a和b后,需要以所需的方式输出数据。”打印(a,b)
将打印a的全部内容,然后打印b的全部内容。如果要打印a中的一个条目,然后打印b中的一个条目,则循环
min(len(a),len(b)`然后是包含更多条目的列表的其余部分

给出了一个例子来说明这一点

a = ['0', '1', '2', '3', '4']
b = ['5', '6', '7', '8', '9']
c = []
c.append(a)
c.append(b)
c

>>> [['0', '1', '2', '3', '4'], ['5', '6', '7', '8', '9']]

如果您想创建一个包含两个元素的列表,您必须循环a和b,将每个元素分别添加到c中,每个a和b。因此,您需要一个双循环来生成一个列表,其中每个元素都是c。

我不确定您到底想做什么;您的代码充满了错误和奇怪的选择

f=open("textfile1.txt","r")
h=open("textfile2.txt","r")
f_list = [x.rstrip("\n") for x in f]
h_list = [x.rstrip("\n") for x in h]

for i in range(max(len(f_list),len(h_list))):
     print (f_list[i],h_list[i])
f=open("textfile1.txt","r")
好的,f是一个文件对象

f = list(f)
现在您已经将文件内容转换为列表了?考虑到您仍然需要迭代内容,这似乎是一种非常低效的方式

for v in range(len(f)):
撇开奇怪的变量命名不谈,您正在迭代f中的每个索引

a=f.rstrip("\n")
这是第一个主要问题

  • 每次迭代都会覆盖a,因此只保留最后的结果

  • 您没有使用索引变量v

  • a=f.rstrip("\n")
    
  • 因为您没有使用索引,所以您试图剥离整个列表,而不是列表中的每一行
  • 你的意思可能是这样的:

    a = f[v].rstrip("\n")
    
    试试这个: 复制上述内容并更改第二个文件的变量,然后列出b

    # iterate over the indexes in a. Assumes that a and b are of the same length.
    for ind in range(len(a)):
        print(a[ind], b[ind])
    

    您的第一个问题是
    rstrip
    不存在。
    第二个问题是不能在列表中使用
    strip

    不管怎样,我写了一个函数,我认为你想要的

    def print_file_and_strip_newlines(fname):
        rtn = ""
        f = open(fname,"r")
        for ln in f:
            #append to rtn a line, stripped of it's newlines
            rtn = rtn + ln.strip('\n')
        print(rtn)
    
    print_file_and_strip_newlines("textfile1.txt")
    print_file_and_strip_newlines("textfile2.txt")
    
    textfile1.txt:

    foo foo foo foo foo foo
    foo foo foo foo foo foo
    foo foo foo foo foo foo
    
    textfile2.txt

    bar bar bar bar bar bar
    bar bar bar bar bar bar
    bar bar bar bar bar bar
    
    输出:

    foo foo foo foo foo foofoo foo foo foo foo foofoo foo foo foo foo foo
    bar bar bar bar bar barbar bar bar bar bar barbar bar bar bar bar bar
    

    有一个神奇的
    zip
    内置函数

    with open('a.txt') as a_file, open('b.txt') as b_file:
        for a_line, b_line in zip(a_file.readlines(), b_file.readlines()):
            print(a_line.strip(), b_line.strip())
    
    ('1', 'a')
    ('2', 'b')
    ('3', 'c')
    ('4', 'd')
    ('5', 'e')
    
    甚至更好的是来自itertools的
    izip
    izip_longest

    更好,因为它们返回iterable而不将所有内容读取到内存中,因此可以处理任意长度的文件

    from itertools import izip
    
    with open('a.txt') as a_file, open('b.txt') as b_file:
        for a_line, b_line in izip(a_file.readlines(), b_file.readlines()):
            print(a_line.strip(), b_line.strip())
    
    ('1', 'a')
    ('2', 'b')
    ('3', 'c')
    ('4', 'd')
    ('5', 'e')
    
    伊兹普大学:

    from itertools import izip_longest
    
    with open('a.txt') as a_file, open('b.txt') as b_file:
        for a_line, b_line in izip_longest(a_file.readlines(), b_file.readlines()):
            print(a_line.strip() if a_line else a_line, b_line.strip() if b_line else b_line)
    
    ('1', 'a')
    ('2', 'b')
    ('3', 'c')
    ('4', 'd')
    ('5', 'e')
    (None, 'f')
    (None, 'g')
    (None, 'h')
    

    简单、清晰、pythonic(这是标准库)

    “它不起作用”它怎么了?发生了什么?与您期望的相比?
    对于f中的i:f=list(f)…a=f.rstrip(“\n”)
    我不知道你的逻辑是什么。这些文本文件中有什么?你能做虚拟输入吗????你在代码的后半部分定义了三个完全不同的东西。首先是一个文件对象,然后是一个不同文件的列表,最后是一个可变整数。这不包括一半的问题。
    h=list(f)
    …在
    h=open(“textfile2.txt”,“r”)中没有任何意义
    。除此之外,还有更多内容,我怀疑您能否从这样一个程序中找到预期的输出。@roganjosh我正在添加并指出各种问题。我在添加答案时进行保存,这样答案就不会丢失。这很公平,但如果您不知道预期的输出或文件结构,请为I in f:I=list(I)选择
    可能被误导了。也许他们想要每一行的整个字符串。我会要求澄清,然后在tbh中投入更多的精力:)