2

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

2
  • You say several times I need to call the output and I just can't get it to a file a can call later -- what does it mean to call a file? That's a new term for me.
    – sarnold
    Jun 20, 2012 at 2:09
  • I need the output to be in a new file. sorry new to this and I know I am doing a bad job of explaining Jun 20, 2012 at 2:10

4 Answers 4

4

There's several approaches you can take:

  1. You can either run the program differently; instead of running:

    ./generate
    

    run

    ./generate > output_file.csv
    

    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.

  2. You can modify your program to write to a specific file. Open the file with something like:

    output = open("output.csv", "w")
    

    and then write output using strings along the lines of

    output.write(each.name + "," + str(each.produce)  + "," + str(each.amount))
    
  3. You could use the same csv module 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.

2
  • I get this using choice 2 ----Traceback (most recent call last): File "C:/Python27/Test2", line 93, in <module> output2.write(each.name+","+ each.produce+"," +each.amount) TypeError: cannot concatenate 'str' and 'int' objects Jun 20, 2012 at 3:12
  • @Adam: Oh bother, I forget which languages are friendly and auto-string numbers in concatenation contexts and which languages want the conversion to be explicit. Updated.
    – sarnold
    Jun 21, 2012 at 1:15
4

Simply redirect output to the file. For example,

C:> python myfile.py > output.txt

2

At the top of the file, open your output file:

outf = open("my_output_file.csv", "wb")

then later:

print >>outf, each.name,each.produce,each.amount
0

Just use CSV writer

add below code:
csvWriter = csv.writer(open('csvFileSource.csv', 'wb'), delimiter=',', quotechar='|',quoting=csv.QUOTE_MINIMAL)
      csvWriter.writerow(each.name + each.produce + each.amount) 

full code :

import csv

file1  = open('csvFileSource.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 listif 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
csvWriter = csv.writer(open('csvFileDestination.csv', 'wb'), delimiter=',', quotechar='|',quoting=csv.QUOTE_MINIMAL)
for each in list:
    csvWriter.writerow(each.name + each.produce + each.amount)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.