[英]Python: Joining files in a list
I am new to Python and am trying to join files that currently exist together in the same list into one file. 我是Python的新手,正在尝试将当前在同一列表中一起存在的文件连接到一个文件中。
They share the same columns. 他们共享相同的列。 What I have looks something like this:
我所拥有的看起来像这样:
File_A
FILE_A
ABCABC
1...1 ...
2...2 ...
3...3 ...
File_B
FILE_B
ABCABC
4...4 ...
5...5 ...
6...6 ...
And what I want to create is: 我要创建的是:
File_C
FILE_C
ABCABC
1...1 ...
2...2 ...
3...3 ...
4...4 ...
5...5 ...
6...6 ...
What I tried is this (in the list "files"): 我试过的是这个(在“文件”列表中):
import fileinput
with open(file_c,'w') as fout:
for line in fileinput.input(file_a, file_b):
fout.write(line);
No dice. 没有骰子。 I end up with repeated lines for eternity.
最后,我为永恒重复了一遍。
I have tried other code as well to no avail. 我也尝试了其他代码也无济于事。 I know that I am doing something stupid, but I am not knowledgeable enough to know what that thing is.
我知道我在做一些愚蠢的事情,但是我不了解这件事是什么。
Thanks. 谢谢。
Just iterate over each file object and write the lines to a new file: 只需遍历每个文件对象,然后将行写入新文件即可:
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)
Depending on how long running the process is, you could get away with 根据流程运行的时间长短,您可以摆脱
with open('output.txt', 'w') as out:
out.writelines(open('file_a').readlines())
out.writelines(open('file_b').readlines()[1:])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.