【问题标题】:Python - combine elements from 2 filesPython - 组合来自 2 个文件的元素
【发布时间】:2018-04-26 00:04:09
【问题描述】:

谁能帮我解决这个问题: 我有两个文件,比如说:

文件 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

有什么想法吗?

【问题讨论】:

  • 您能否将最后一行替换为:outline.write(' '.join(s + [ss[1]])) 并告诉我们它是否有效(我没有运行它,但应该稍作修改)。
  • 它可以工作,但它不会返回循环遍历整个文件 1。它仅将文件 1 的第一行与文件 2 进行比较
  • 是的,因为你只有在满足条件的情况下才会做某事。你也应该处理else
  • 如果你会使用pandas,就像使用merge函数一样简单

标签: python file merge


【解决方案1】:

我看到的错误是您试图将列表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. for循环中嵌入open文件语句,如:

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

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

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

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

【讨论】:

  • 我试过了,但第一个循环不起作用。就像它需要第一行,与文件 2 比较然后退出循环。它不会返回文件 1 来检查其他行
  • 你是对的:我的解决方案中有两个错误,我将解决这些错误,并附上解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多