【问题标题】:Python: Joining files in a listPython:加入列表中的文件
【发布时间】:2014-11-17 22:02:12
【问题描述】:

我是 Python 新手,正在尝试将当前存在于同一个列表中的文件合并到一个文件中。

它们共享相同的列。我所拥有的看起来像这样:

文件_A
A B C
1...
2...
3...

文件_B
A B C
4...
5...
6...

而我想要创建的是:

文件_C
A B C
1...
2...
3...
4...
5...
6...

我尝试的是这个(在“文件”列表中):

import fileinput
with open(file_c,'w') as fout:
    for line in fileinput.input(file_a, file_b):
        fout.write(line); 

没有骰子。我最终得到了永恒的重复线条。

我也尝试了其他代码,但无济于事。我知道我在做一些愚蠢的事情,但我没有足够的知识知道那是什么。

谢谢。

【问题讨论】:

  • 我想这些是csv 文件?

标签: python list file concatenation


【解决方案1】:

只需遍历每个文件对象并将这些行写入一个新文件:

with open("input1.txt") as f, open("input2.txt") as f2,open("output.txt","w") as f3:
    f2.next() # skip header to avoid writing  A B C twice
    for line in f:
        f3.write(line)
    f3.write("\n") # separate last line from file 1 and first of file 2
    for line in f2:
        f3.write(line)

【讨论】:

  • 谢谢!感谢您的帮助。
【解决方案2】:

根据进程运行的时间长短,您可以侥幸逃脱

with open('output.txt', 'w') as out:
    out.writelines(open('file_a').readlines())
    out.writelines(open('file_b').readlines()[1:])

【讨论】:

    猜你喜欢
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-27
    • 2015-05-29
    • 2012-12-21
    • 2017-12-21
    相关资源
    最近更新 更多