我在将2个.txt文件合并为1个txt文件时遇到问题。我可以合并它们,但是我需要按ID将它们合并到同一行中
此代码合并,但在txt下面
import shutil;
print("Enter 'x' for exit.");
filename1 = input("Enter first file name to merge: ");
if filename1 == 'x':
exit();
else:
filename2 = input("Enter second file name to merge: ");
filename3 = input("Create a new file to merge content of two file inside this file: ");
print();
print("Merging the content of two file in",filename3);
with open(filename3, "wb") as wfd:
for f in [filename1, filename2]:
with open(f, "rb") as fd:
shutil.copyfileobj(fd, wfd, 1024*1024*10);
print("\nContent merged successfully.!");
print("Want to see ? (y/n): ");
check = input();
if check == 'n':
exit();
else:
print();
c = open(filename3, "r");
print(c.read());
c.close();
我拥有的:(输入文件)
文本1.txt:
Id x y
1 6655.5 -3132.0
文本2.txt:
Id e n z
1 111 222 333
我想得到例如:(预期输出)
Id x y e n z
1 6655.5 -3132.0 111 222 333
假设两个文本文件中ID的数量和顺序相同,可以执行以下操作:
(注意:这将适用于较小的文件,因为下面的代码将整个文本文件读入内存。如果您的文件非常大,那么您需要使用一些生成器来调整它
相关问题 更多 >
编程相关推荐