繁体   English   中英

Python-合并2个文件中的元素

[英]Python - combine elements from 2 files

谁能帮我这个忙:我有两个文件,说:

文件1:

 A1 B1 C1 D1 
 A2 B2 C2 D2 
 A3 B3 C3 D3 
 A4 B4 C4 D4 

文件2:

A1 E1 
A4 E4 

所需的输出:

A1 B1 C1 D1 E1
A2 B2 C2 D2 
A3 B3 C3 D3 
A4 B4 C4 D4 E4 

这是我得到的,它将无法正常工作:

>>>    for line1 in file1.readlines ():
>>>       s = line1.split ()
>>>        # do stuff...
>>>       for line2 in file2.readlines ():
>>>            ss = line2.split ()
>>>            if s [0] == ss[0]:
>>>                outfile.write (s + " " + ss [1])
>>>        # do some more stuff

有什么想法吗?

我看到的错误是您正在尝试将列表s与两个字符串连接起来,这是不允许的。 正确的方法是将附加元素ss[1]附加到列表s ,然后打印结果。 或者只是将line1用作字符串。

您还需要处理s[0] != ss[0] ,在这种情况下,您只想打印出line1

关于readlines一个重要说明是,它不会在每次调用文件时自动将文件指针重置为文件的开头。 而是,一旦文件指针到达末尾,它将停留在那里。

几乎没有其他选择。

  1. 在搜索循环之前添加file2.seek(0)语句

  2. 将文件内容加载到列表中,并遍历列表,例如:

    file1_content = open('file1.ext', 'r').readlines()

    for line1 in file1_content: ...

  3. open文件语句嵌入到for循环中,例如:

    for line2 in open('file2.ext', 'r')

    请注意,文件是可迭代的,因此您不需要readlines()

当然,最佳解决方案取决于几个因素。 我将在这里选择#3,因为我认为它更像Python:

outfile = open('outfile.ext', 'w')
for line1 in open('file1.ext', 'r'):
    s = line1.split ()

    # reset search flag
    found = False

    # start search loop
    for line2 in open('file2.ext', 'r'):
        ss = line2.split ()

        # search for a match
        if s [0] == ss[0]:
           # match found: set the flag 
           found = True

           # write to file with additional element appended (*)
           outfile.write (line1.strip() + ' ' + ss[1] + '\n'))

    # No match found: just save the original line     
    if not found:
       outfile.write(line1)

(*)应该有一个换行符,我们将在附加最后一个元素之前将其删除。 当您写入文件时,我们必须将其添加回去。

也可以在这里查看: https//eval.in/994943或在此处查看变体https://eval.in/994944

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM