将两个不同文件的Python合并行合并为一个列表

时间:2018-07-29 15:10:18

标签: python list file merge

我正在尝试根据两个不同文件中的行来构建列表。

File1.txt

['2.02', '-3.88', '15.25']
['4.40', '-2.36', '14.97']
['5.44', '0.34', '7.34']
['5.76', '0.41', '7.60']
['5.35', '0.19', '13.95']

File2.txt

['P1']
['P2']
['P3']
['P4']
['P5']

理想的输出

['2.02', '-3.88', '15.25', 'P1']
['4.40', '-2.36', '14.97', 'P2']
['5.44', '0.34', '7.34', 'P3']
['5.76', '0.41', '7.60', 'P4']
['5.35', '0.19', '13.95', 'P5']

我试图简单地添加行

combined = open('file1.txt').readlines() + open('line2.txt').readlines()

输出

["['2.02', '-3.88', '15.25']\n", "['4.40', '-2.36', '14.97']\n", "['5.44', '0.34', '7.34']\n", "['5.76', '0.41', '7.60']\n", "['5.35', '0.19', '13.95']\n", 'P1\n', 'P2\n', 'P3\n', 'P4\n', 'P5\n']

我还写了一个函数,试图将两者合并到第三个文件file3.txt

def combiner():
with open("file1.txt", 'r') as file1:
    with open('file2.txt', 'r') as file2:
        with open('file3.txt',"w") as file3:
            clines = file1.readlines()
            plines = file2.readlines()
   #Write to third file
            for i in range(len(clines)):
                line = clines[i].strip() + plines[i]
                file3.write(line)

但是它仍然写在2个不同的列表中

cat file3.txt

['2.02', '-3.88', '15.25']['P1']
['4.40', '-2.36', '14.97']['P2']
['5.44', '0.34', '7.34']['P3']
['5.76', '0.41', '7.60']['P4']
['5.35', '0.19', '13.95']['P5']

最好是返回此类列表的函数。

2 个答案:

答案 0 :(得分:3)

即使文件中的行类似于列表,您实际上还是将它们视为字符串。您可以使用ast.literal_eval将字符串评估为列表,将其组合,然后将其写入其他文件

from ast import literal_eval

def combiner(infile1, infile2, outfile):
    with open(infile1) as f1, open(infile2) as f2, open(outfile, 'w+') as f3:
        f1_lists = (literal_eval(line) for line in f1)
        f2_lists = (literal_eval(line) for line in f2)
        for l1, l2 in zip(f1_lists, f2_lists):
            f3.write(str(l1+l2) + '\n')  # This could also be print(l1+l2, file=f3)

答案 1 :(得分:1)

使用pandas

import ast

df1 = pd.read_csv(file1, sep='\n', header=None, names=['data'])
df2 = pd.read_csv(file2, sep='\n', header=None, names=['data'])

parse = lambda d: d.transform(ast.literal_eval)

df1['data'] = parse(df1.data)
df2['data'] = parse(df2.data)

然后就

df1 + df2

    data
0   [2.02, -3.88, 15.25,  P1]
1   [4.40, -2.36, 14.97,  P2]
2   [5.44, 0.34,  7.34,   P3]
3   [5.76, 0.41,  7.60,   P4]
4   [5.35, 0.19,  13.95,  P5]