我是一名Python初學者,我試圖比較兩個csv文件中的兩個字段(時間戳),如果它們匹配,則將它們合併到第三個文件中。輸入文件看起來像:比較和合並兩個CSV文件中的字段
文件1:
name,time,operation
Cassandra,2015-10-06T15:07:22.333662984Z,INSERT
Cassandra,2015-10-06T15:07:24.334536781Z,INSERT
Cassandra,2015-10-06T15:07:27.339662984Z,READ
文件2:
name,time,host,instance,type,type_instance,value
cpu_value,2015-10-06T15:07:22.333662984Z,vm1-VirtualBox,0,cpu,user,24874
cpu_value,2015-10-06T15:07:24.334536781Z,vm1-VirtualBox,0,cpu,nice,592
cpu_value,2015-10-06T15:07:27.339662984Z,vm1-VirtualBox,0,cpu,system,2932
這是我到目前爲止已經試過:
import csv
with open('f1.csv', 'rb') as f1, open ('f2.csv', 'rb') as f2:
next(f1) #skip line 1
next(f2) #skip line 1
reader1 = csv.reader(f1)
reader2 = csv.reader(f2)
for row1 in reader1:
for row2 in reader2:
if row1[1] == row2[1]:
data = [row1[0],row2[0]]
print data
然後,我得到這個錯誤:
['cpu_value', 'Cassandra']
Traceback (most recent call last):
File "merger.py", line 10, in <module>
if row1[1] == row2[1]:
IndexError: list index out of range
更新
預期輸出:
Cassandra,2015-10-06T15:07:22.333662984Z,INSERT,cpu_value,vm1-VirtualBox,0,cpu,user,24874
Cassandra,2015-10-06T15:07:24.334536781Z,INSERT,cpu_value,vm1-VirtualBox,0,cpu,nice,592
Cassandra,2015-10-06T15:07:27.339662984Z,READ,cpu_value,vm1-VirtualBox,0,cpu,nice,592
您可以通過這個link訪問這些文件。如果你有任何想法,請告訴我。謝謝。
什麼是您預期的輸出? – aerokite
@AerofoilKite我更新了帖子。 – arazx
是否有可能這些csv文件之一有一個看似空的行或只有沒有足夠的字段的行?這就是錯誤信息暗示的原因。如果你不知道,你應該考慮添加一個鏈接到這兩個文件,以便其他人可以檢查他們。 –