我被鼓励走出我的舒适区并使用python几乎没有经验,现在我被卡住了。我正在尝试比较两个CSV文件(fileA.csv和fileB.csv),并将任何缺少的用户行从fileB.csv附加到fileA.csv。我可以比较的唯一字段是用户的名字和姓氏(在这种情况下,它是每个文件的行[0]和行[2])。
根据我的理解,您无法将信息附加到您当前打开的文件中,因此我可以接受建议,而无需创建第三个文件(如果可能)。下面有我在正确的轨道,但有很多数据,所以我需要一个循环。请帮忙。
import csv
reader1 = csv.reader(open('fileA', 'rb'), delimiter=',', quotechar='|')
row1 = reader1.next()
reader2 = csv.reader(open('fileB', 'rb'), delimiter=',', quotechar='|')
row2 = reader2.next()
##For Loop...
if (row1[0] == row2[0]) and (row1[2] == row2[2]):
## Compare next
else:
## Append entire row to fileA.csv
示例FileA.csv:
John,Thomas,Doe,some,other,stuff
Jane, ,Smith,some,other,stuff
示例FileB.csv:
John, ,Doe,other,personal,data
Jane,Elizabeth,Smith,other,personal,data
Robin,T,Williams,other,personal,data
应该从FileB追加到FileA的唯一行是Robin的完整行,以便FileA看起来像:
DesiredResult_FileA:
John,Thomas,Doe,some,other,stuff
Jane, ,Smith,some,other,stuff
Robin,T,Williams,other,personal,data
答案 0 :(得分:1)
首先将文件A中的信息存储在内存中。
然后,以附加模式重新打开文件A,并循环遍历文件B.然后可以将来自B中找不到的任何名称添加到文件A中:
csv_dialect = dict(delimiter=',', quotechar='|')
names = set()
with open('fileA', 'rb') as file_a:
reader1 = csv.reader(file_a, **csv_dialect)
next(reader1)
for row in reader1:
names.add((row[0], row[2]))
# `names` is now a set of all names (taken from columns 0 and 2) found in file A.
with open('fileA', 'ab') as file_a, open('fileB', 'rb') as file_b:
writer = csv.writer(file_a, **csv_dialect)
reader2 = csv.reader(file_b, **csv_dialect)
next(reader2)
for row in reader2:
if (row[0], row[2]) not in names:
# This row was not present in file A, add it.
writer.writerow(row)
合并的with
行需要Python 2.7或更高版本。在早期的Python版本中,只需嵌套两个语句:
with open('fileA', 'ab') as file_a:
with open('fileB', 'rb') as file_b:
# etc.
答案 1 :(得分:0)
您可以尝试pandas,这可能会帮助您更轻松地处理csv文件,并且似乎更具可读性:
import pandas as pd
df1 = pd.read_csv('FileA.csv', header=None)
df2 = pd.read_csv('FileB.csv', header=None)
for i in df2.index:
# Don't append if that row is existed in FileA
if i in df1.index:
if df1.ix[i][0] == df2.ix[i][0] and df1.ix[i][2] == df2.ix[i][2]: continue
df1 = df1.append(df2.ix[i])
df1.to_csv('FileA.csv', index=None, header=None)