如何在 Python 中合并来自不同 txt 文件的某些列数据?

how to merge some columns data from different txt files in Python?

我有一些txt文件,需要将其中的某些列提取出来并存储在一个txt文件中。

a1.txt:

53, 42
54, 38
55, 37
57, 48

b1.txt:

45, 15, 30, 2
16, 59, 31, 4
87, 09, 32, 5
58, 16, 33, 3

我需要的是 c.txt(将b1.txt的最后一列添加到a1.txt):

53, 42, 2
54, 38, 4
55, 37, 5
57, 48, 3

b.txt 的第 4 列应添加到 a.txt 的第 5 列。然后创建一个新文件c.txt。 我尝试了一些代码,但没有用。 cmd 说 "TypeError: list indice must be integers, not srt"。 我不知道如何将不同文件的列合并在一起。希望有人能帮我修改代码。非常感谢!

def readf(filename):
    lines=file(filename).readlines()
    for i in lines:
        data=i.split()
    return data

fa=readf('a1.txt')
fb=readf('b1.txt')

lines=[]
for i in fa:
    s=fa[i]+fb[3]
    s+='\n'
    lines.append(s)

with open ('c.txt','w') as f:
    f.writelines(lines)
    f.close>

在以下命令中,您已将字符串作为索引传递给列表:

for i in fa:
    s=fa[i]+fb[3]

注意您正在迭代文件对象!

但作为解决此类问题的更好方法,我建议使用 csv 模块。

from itertools import izip_longest
import csv
with open('a1.txt', 'rb') as csv1,open('b1.txt', 'rb') as csv2,open('c.txt', 'w') as out:
     spam1 = csv.reader(csv1, delimiter=',')
     spam2 = csv.reader(csv2, delimiter=',')
     last_column=list(izip_longest(*spam2))[-1]
     for i,j in  izip_longest(spam1,last_column):
        out.write(','.join([t.strip(';') for t in i])+','+j+'\n')

此处 last_column=list(izip_longest(*spam2))[-1] 将为您提供 b1.txt 的最后一列,izip_longest(spam1,last_column) 将为您提供以下列表:

[(['53', ' 42;'], ' 2;'), (['54', ' 38;'], ' 4;'), (['55', ' 37;'], ' 5;'), (['57', ' 48; '], ' 3;')]

因此您可以使用 ; 剥离元素并写入文件。

如果可以忽略 ; 您可以将最后一行更改为:

out.write(','.join(i)+','+j+'\n')
def read_file(file_name):
    col_data = []
    with open(file_name) as data_file:
        for data in data_file.readlines():
            col1, col2, col3, col4 = data.split(",")
            col_data.append(col4[:-1])
    return col_data

numbers = read_file("b1.txt")

with open("a1.txt") as a_file:
    with open("new_file.txt", "w") as new_file:
        lines = a_file.readlines()
        for line in xrange(len(lines)):
            new_file.write(lines[line][:-1] + " ,"+numbers[line]+"\n")

由于您需要使用 ,; 作为参数来拆分文本,因此您可以使用 re 来完成这项工作。然后就是写第一个文件的所有属性和第二个文件的最后一个属性。

import re
with open("a.txt", 'r') as f:
    a1 = [re.findall(r"[\w']+", line) for line in f]
with open("b.txt", 'r') as b:
    b1 = [re.findall(r"[\w']+", line) for line in b]
with open("c.txt", 'w') as c:
    for x,y in zip(a1,b1):
        c.write("{},{}\n".format(",".join(x),y[-1]))  

这会创建文件 c,看起来像

53,42,2 
54,38,4 
55,37,5 
57,48,3

你用pandas怎么样:

import pandas as pd
a1 = pd.read_csv('a1.txt', header= None ,escapechar=';')
b1 = pd.read_csv('b1.txt', header= None)

a1[2] = b1[3]

a1.to_csv('c.txt',index=False,header= False)

c.txt:

53, 42, 2;
54, 38, 4;
55, 37, 5;
57, 48, 3;