1

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

1
  • 1
    you do not define writer or close the outfile Commented Jun 24, 2016 at 18:31

1 Answer 1

4

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]])
Sign up to request clarification or add additional context in comments.

1 Comment

It's been the close.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.