比较两个CSV文件并将缺失值(在不同的行)写入文件 Python

0 投票
2 回答
1625 浏览
提问于 2025-04-18 16:30

我需要比较两个文件,把缺失的值写到另一个文件里。

文件1(File1.csv)内容:

Monday, sports, swimming
Tuesday, study, running
Wednesday, jog, sprint
Thursday, nothing, Play

文件2(File2.csv)内容:

Monday
Wednesday

输出文件(output_File)应该是:

Tuesday, study, running
Thursday, nothing, Play

我尝试过的方法:

import csv

f1 = file('C:\File1.csv', 'rb')
f2 = file('C:File2.csv', 'rb')
f3 = file('C:\output_file.csv', 'wb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)
masterlist = [row for row in c2]
for hosts_row in c1:
    for master_row in masterlist:
        results_row = hosts_row
        if hosts_row[0] == master_row[0]:
                print results_row
                c3.writerow(results_row)

输出文件(Output_file.csv)内容:

Monday, sports, swimming
Wednesday, jog, sprint

2 个回答

0

稍微简短一点,而且不需要用到 cvs(其实你根本不需要它):

file1 = [line.strip() for line in open('File1.csv')]
file2 = [line.strip() for line in open('File2.csv')]

with open('output_File.cvs', 'w') as f:
    for line in file1:
        if not line.split(',')[0] in file2:
            f.write(line + '\n')

补充:喜欢一行代码的朋友们可以用下面的代码替代这个循环:

f.writelines('\n'.join(filter(lambda l: not l.split(',')[0] in file2, file1)))
0

在编程中,有时候我们需要处理一些数据,这些数据可能来自不同的地方,比如用户输入、文件或者网络请求。为了让程序能够理解这些数据,我们通常需要将它们转换成一种特定的格式。

比如说,如果我们从一个网页上获取了一些信息,这些信息可能是以文本的形式存在的。为了在程序中使用这些信息,我们可能需要把它们转化为一个对象,这样就可以更方便地进行操作了。

这个过程就像是把原材料加工成成品一样,原材料可能是杂乱无章的,而成品则是我们可以直接使用的东西。

在编程中,常见的转换方式有很多,比如将字符串(文本)转换成数字,或者将一个列表转换成字典(键值对的形式)。这些转换可以帮助我们更好地管理和使用数据。

总之,数据转换是编程中一个非常重要的环节,它让我们的程序能够更智能地处理各种信息。

import csv

f1 = file('C:\File1.csv', 'rb')
f2 = file('C:File2.csv', 'rb')
f3 = file('C:\output_file.csv', 'wb')
c1 = csv.reader(f1)
c2 = csv.reader(f2)
c3 = csv.writer(f3)
masterlist = [row[0] for row in c2]

for hosts_row in c1:
    if hosts_row[0] not in masterlist:
        print hosts_row
        c3.writerow(hosts_row)

撰写回答