如何按ID合并文件?

2024-04-19 06:00:15 发布

您现在位置:Python中文网/ 问答频道 /正文

我在将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


Tags: 文件totxtidforinputexitopen
1条回答
网友
1楼 · 发布于 2024-04-19 06:00:15

假设两个文本文件中ID的数量和顺序相同,可以执行以下操作:

with open('text1.txt', 'r') as f1, open('text2.txt', 'r') as f2:
    f1_text = f1.read().splitlines()
    f2_text = f2.read().splitlines()
with open('text3.txt', 'w+') as f3:
    for i, item in enumerate(f1_text):
        value1 = f1_text[i].split(None, 1)[1].rstrip('\n')
        value2 = f2_text[i].split(None, 1)[1].rstrip('\n')
        if i == 0:
            i = 'Id'
        f3.write(str(i) + ' ' + value1 + ' ' + value2 + '\n')

with open('text3.txt', 'r') as f3:
    print(f3.read())

Input:
  -
"TEXT1.txt"
Id x y
1 6655.5 -3132.0
2 1122.3 -1234.0
3 4455.6 -5678.9
  -
"TEXT2.txt"
Id e n z 
1 111 222 333
2 444 555 666
3 777 888 999  
=====
Output:
"TEXT3.txt"
## Id x y e n z 
## 1 6655.5 -3132.0 111 222 333
## 2 1122.3 -1234.0 444 555 666
## 3 4455.6 -5678.9 777 888 999

(注意:这将适用于较小的文件,因为下面的代码将整个文本文件读入内存。如果您的文件非常大,那么您需要使用一些生成器来调整它

相关问题 更多 >