我需要将我必须的代码的输出写入一个文件,以便稍后调用它。我需要调用输出而不是原始 test1 文件。我拥有的使输出的代码在下面并且工作正常,我只是无法将它放到稍后可以调用的文件中。
import csv
file1 = open('C:/Users/Gallatin/Documents/adamenergy.csv',"r") #Open CSV File in Read Mode
reader = csv.reader(file1) #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:
print each.name,each.produce,each.amount
通过打印,它会正确生成我想要的输出,但我需要将此输出写入文件,以便稍后使用 ndiff 调用它以与另一个 csv 文件进行比较我将通过上面类似的代码运行