私は 2 つの csv ファイルを持っています ( ) csv ファイルから合計された合計を含むリストを印刷することができます。私はこのコードを使用します:
import csv
import difflib
file = open('test1.csv',"rb") #Open CSV File in Read Mode
reader = csv.reader(file) #Create reader object which iterates over lines
class Object: #Object to store unique data
def __init__(self, name, produce, amount):
self.name = name
self.produce = produce
self.amount = amount
rownum = 0 #Row Number currently iterating over
list = [] #List to store objects
def checkList(name, produce, amount):
for object in list: #Iterate through list
if object.name == name and object.produce == produce: #Check if name and produce combination exists
object.amount += int(amount) #If it does add to amount variable and break out
return
newObject = Object(name, produce, int(amount)) #Create a new object with new name, produce, and amount
list.append(newObject) #Add to list and break out
for row in reader: #Iterate through all the rows
if rownum == 0: #Store header row seperately to not get confused
header = row
else:
name = row[0] #Store name
produce = row[1] #Store produce
amount = row[2] #Store amount
if len(list) == 0: #Default case if list = 0
newObject = Object(name, produce, int(amount))
list.append(newObject)
else: #If not...
checkList(name, produce, amount)
rownum += 1
for each in list:
file1 = each.name, each.produce, each.amount #END OF FILE 1
file = open('test2.csv',"rb") #Open CSV File in Read Mode
reader = csv.reader(file) #Create reader object which iterates over lines
class Object: #Object to store unique data
def __init__(self, name, produce, amount):
self.name = name
self.produce = produce
self.amount = amount
rownum = 0 #Row Number currently iterating over
list = [] #List to store objects
def checkList(name, produce, amount):
for object in list: #Iterate through list
if object.name == name and object.produce == produce: #Check if name and produce combination exists
object.amount += int(amount) #If it does add to amount variable and break out
return
newObject = Object(name, produce, int(amount)) #Create a new object with new name, produce, and amount
list.append(newObject) #Add to list and break out
for row in reader: #Iterate through all the rows
if rownum == 0: #Store header row seperately to not get confused
header = row
else:
name = row[0] #Store name
produce = row[1] #Store produce
amount = row[2] #Store amount
if len(list) == 0: #Default case if list = 0
newObject = Object(name, produce, int(amount))
list.append(newObject)
else: #If not...
checkList(name, produce, amount)
rownum += 1
for each in list:
file2 = each.name, each.produce, each.amount #END OF FILE 2
これはすべて正常に機能します。私が何をしているかを確認できるように提供しました。
そこで、作成した 2 つの新しいファイルの違いを取得する必要があります。これが私が立ち往生した場所です。これを試しましたが、うまくいきませんでした
diff=difflib.ndiff('file1',"rb"), ('file2',"rb")
try:
while 1:
print diff.next(),
except:
pass
2 つの新しいファイルの違いを生成する必要があるため、違いを確認できますか? 実行するとエラーは発生しませんが、出力はありません