-1
我有兩個CSV文件。 data.csv和data2.csv。按行和列讀取並比較2個CSV文件
我想首先將兩個數據文件剝離成我感興趣的數據。我已經用data.csv計算了這部分內容。然後,我想按行進行比較,以確保是否缺少一行來添加它。
接下來,我想看看第2列。如果有一個價值有那麼我想寫信給第3列,如果在第3列數據,然後寫入4等
我現在的程序看起來像母豬。需要一些指導
哦,我使用Python V3.4
__author__ = 'krisarmstrong'
#!/usr/bin/python
import csv
searched = ['aircheck', 'linkrunner at', 'onetouch at']
def find_group(row):
"""Return the group index of a row
0 if the row contains searched[0]
1 if the row contains searched[1]
etc
-1 if not found
"""
for col in row:
col = col.lower()
for j, s in enumerate(searched):
if s in col:
return j
return -1
inFile = open('data.csv')
reader = csv.reader(inFile)
inFile2 = open('data2.csv')
reader2 = csv.reader(inFile2)
outFile = open('data3.csv', "w")
writer = csv.writer(outFile, delimiter=',', quotechar='"', quoting=csv.QUOTE_ALL)
header = next(reader)
header2 = next(reader2)
"""Built a list of items to sort. If row 12 contains 'LinkRunner AT' (group 1),
one stores a triple (1, 12, row)
When the triples are sorted later, all rows in group 0 will come first, then
all rows in group 1, etc.
"""
stored = []
writer.writerow([header[0], header[3]])
for i, row in enumerate(reader):
g = find_group(row)
if g >= 0:
stored.append((g, i, row))
stored.sort()
for g, i, row in stored:
writer.writerow([row[0], row[3]])
inFile.close()
outFile.close()
那麼問題是什麼?錯誤還是別的? – Marcin 2014-10-29 03:30:09
Marcin,上面的代碼有效。沒有錯誤。我想添加另一篇文章,其中我比較了2個CSV文件。如果第一個CSV文件中缺少一行,請添加它。如果第2列已滿,如果第2列和第3列已滿,則將數據添加到第3列 – 2014-10-29 21:36:48