I need to write the output of the code I have to a file so I can call it later. I need to call the output not the original test1 file. the code I have that makes the output is below and works fine, I just can’t get it to a file a can call later.
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
With the print it generates the output i want correctly, but i need to write this output to a file so I can call it later using ndiff to compare to another csv file I will run through similar code above
There’s several approaches you can take:
You can either run the program differently; instead of running:
run
This uses shell redirection to save the standard output to whatever file you specify. This is extremely flexible and very easy to build into future scripts. It’s especially awesome if you accept input on standard input or via a named file, it makes your tool extremely flexible.
You can modify your program to write to a specific file. Open the file with something like:
and then write output using strings along the lines of
You could use the same
csvmodule to also write files. This might be the better approach for long-term use, because it’ll automatically handle complicated cases of inputs that include,characters and other difficult cases.