简体   繁体   中英

Python: Writing to csv-file

I am trying to read a csv-style file and create another one. Here is the (simplified) code.

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))

Neither of the writerow statements generate output.

The file is created, but is empty.

The print statement creates 'expected' ouput.

I have also tried already csv.DictWriter with no success either.

I have looked at the various simlar questions, but can't see any difference.

I am using Py 3.3.3 on a win 7 machine.

EDIT:

the writer got lost be code simplification

Your code doesn't define a writer.

Add writer = csv.writer(outfile) and then close the outfile and it should work. Using the with idiom makes the code cleaner.

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]])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM