如何通过ID合并文件?

时间:2019-04-10 13:58:29

标签: python shutil

将2个.txt文件合并为1个txt文件时遇到问题。我可以合并它们,但是我需要按ID在同一行中合并它们。然后,我必须在同一行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();

我所拥有的:(输入文件)

text1.txt:

  

Id x y
  1 6655.5 -3132.0

text2.txt:

  

Id e n z
  1111222333

我想举个例子:(预期输出)

  

Id x y e n z
  1 6655.5 -3132.0 111222333

1 个答案:

答案 0 :(得分:0)

假设两个文本文件中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

(注意:这将适用于较小的文件,因为下面的代码将整个文本文件读入内存。如果文件很大,则需要使用一些 generator 进行调整) / p>