将csv写入文件

时间:2012-06-20 02:06:59

标签: python csv

我需要将我拥有的代码的输出写入文件,以便稍后调用。我需要调用输出而不是原始的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文件进行比较我将通过上面的类似代码运行

由于

4 个答案:

答案 0 :(得分:4)

只需将输出重定向到文件即可。 例如,

C:> python myfile.py> output.txt的

答案 1 :(得分:4)

您可以采取以下几种方法:

  1. 您可以以不同方式运行程序;而不是跑步:

    ./generate
    

    运行

    ./generate > output_file.csv
    

    这使用shell重定向将标准输出保存到您指定的任何文件。这非常灵活,很容易构建到将来的脚本中。如果您接受标准输入或命名文件的输入,它会特别棒,它会使您的工具非常灵活。

  2. 您可以将程序修改为write to a specific file。用以下内容打开文件:

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

    然后使用

    行的字符串写输出
    output.write(each.name + "," + str(each.produce)  + "," + str(each.amount))
    
  3. 您可以使用相同的csv module to also write files。这可能是长期使用的更好方法,因为它会自动处理包含,个字符和其他疑难案例的复杂输入案例。

答案 2 :(得分:2)

在文件顶部,打开输出文件:

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

然后:

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

答案 3 :(得分:0)

只需使用CSV编辑器

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

完整代码:

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)