使用python将数值相近的文本文件合并成一个文件。

问题描述 投票:0回答:1

我在网站上搜索了一下,但找不到任何与我想完成的任务完全相似的东西。我有2个文本文件,我想根据每个文件中的第一行(让我们称这行为x)合并成一个文件。例如,如果x存在于file1和file2中,那么我想取x并在其行上显示file1和file2的信息。注意,file1包含一个头。下面是每个文件读取方式的预览。

文件1:

X, DES1, DES2, DES3, NUMBERS
123, text, text, text, 456
321, text, text, text, 43222
124, text, text, text, 3254
125, text, text, text, 2352634
279, text, text, text, 3243
567, text, text, text, 00001
345, text, text, text, 02

文件2:

123, 152352364
124, 32535
125, 745734
345, 4000 

以此类推。file2中的每个元素(或x)都存在于file1中。然而,file1中包含了file2中没有的x的其他值。我还能把两个文件中的数据合并到一个新文件中吗?下面是我试过的,但我在打印语句上得到一个KeyError。我确信代码是非常错误的,仅供参考。

f1 = {}
with open ("file1.txt") as my1:
    for line in my1.readlines():
        f1[line.split(",")[0]] = line.strip().split(",")[1:]

f2={}
with open ("file2.txt") as my2:
    for line in f.readlines():
        f2[line.split(",")[0]] = line.strip().split(",")[1:]

for key in f1.keys():
    print(key, str.join(",",f1[key]), str.join(",",f2[key]))

任何帮助将是感激的。我知道我很可能要大量重做或废掉我目前所拥有的东西。我的预期输出将看起来如下。

X, DES1, DES2, DES3, NUMBERS, NEWNUMB        
123, text, text, text, 456, 152352364    
321, text, text, text, 43222, 0    
124, text, text, text, 3254, 32535    
125, text, text, text, 2352634, 745743    
279, text, text, text, 3243, 0    
567, text, text, text, 00001, 0    
345, text, text, text, 02, 4000    
python file dictionary text-files
1个回答
1
投票

你没有跳过标题行从 file1.txt

f1 = {}
with open ("file1.txt") as file1:
    next(file1)  # skip the header (first line)
    for line in file1:  # for loop iterates over lines by default
        f1[line.split(",")[0]] = line.strip().split(",")[1:]

f2 = {}
with open ("file2.txt") as file2:
    for line in file2:
        f2[line.split(",")[0]] = line.strip().split(",")[1:]


# generate the contents of the new file
lines = [
    ['X', 'DES1', 'DES2', 'DES3', 'NUMBERS', 'NEWNUMB']  # headings
]
for key, value in f1.items():
    # get will return the second argument if the key doesn't exist
    new_num = f2.get(key, ['0'])
    # unpack the values into a new list and append it to lines
    lines.append([key, *value, *new_num])

for line in lines:
    print(','.join(line))

你需要对你的代码进行更多必要的修改。你应该自己去玩玩,试着去做。我只是简单的修正了错误。

disciple@diptangsu:~/Desktop/sample$ cat file1.txt 
X, DES1, DES2, DES3, NUMBERS
123, text, text, text, 456
321, text, text, text, 43222
124, text, text, text, 3254
125, text, text, text, 2352634
279, text, text, text, 3243
567, text, text, text, 00001
345, text, text, text, 02
disciple@diptangsu:~/Desktop/sample$ cat file2.txt 
123, 152352364
124, 32535
125, 745734
345, 4000 
disciple@diptangsu:~/Desktop/sample$ python3 code.py 
X,DES1,DES2,DES3,NUMBERS,NEWNUMB
123, text, text, text, 456, 152352364
321, text, text, text, 43222,0
124, text, text, text, 3254, 32535
125, text, text, text, 2352634, 745734
279, text, text, text, 3243,0
567, text, text, text, 00001,0
345, text, text, text, 02, 4000

如果你不知道什么是 next 是,我建议你阅读一下python中的生成器。

© www.soinside.com 2019 - 2024. All rights reserved.