Python:写入csv文件

时间:2016-06-24 18:26:13

标签: python csv

我正在尝试读取csv样式的文件并创建另一个。 这是(简化)代码。

import os
import csv
import sys

fn = 'C:\mydird\Temp\xyz'
ext = '.txt'
infn = fn+ext
outfn = fn+'o'+ext


infile = open(infn, newline='')
outfile = open(outfn, 'w', newline='')

try:
    reader = csv.reader(infile, delimiter=',', quotechar='"')  # creates the reader object
    writer = csv.writer(outfile, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)

    for row in reader:   # iterates the rows of the file in orders
        if reader.line_num == 1 :
            print("Header")
            writer.writerow(['Date',
                'XY'])                      # ####### Does not work
        else:
#            Do something
            print(row[0],
                row[3])                     # ####### Works
            writer.writerow([row[0],
                row[3]])                    # ####### Does not work
finally:
    infile.close()      # closing

sys.exit(0))

两个writerow语句都没有生成输出。

文件已创建,但为空。

print语句创建'期望'输出中。

我也尝试过csv.DictWriter,但也没有成功。

我查看了各种类似的问题,但看不出任何差异。

我在win 7机器上使用Py 3.3.3。

修改

作家迷失了代码简化

1 个答案:

答案 0 :(得分:4)

您的代码没有定义作者。

添加writer = csv.writer(outfile),然后关闭outfile,它应该可以工作。使用with成语使代码更清晰。

import csv

fn = 'C:\mydird\Temp\xyz'
ext = '.txt'
infn = fn+ext
outfn = fn+'o'+ext

with open(infn) as rf, open(outfn, 'w') as wf:
    reader = csv.reader(rf, delimiter=',', quotechar='"')
    writer = csv.writer(wf)
    for row in reader:   # iterates the rows of the file in orders
        if reader.line_num == 1 :
           print("Header")
           writer.writerow(['Date', 'XY'])
        else:
           # do something
            print(row[0], row[3])
            writer.writerow([row[0], row[3]])