Search code examples
pythonfunctionprogram-entry-pointwriter

writer.writerow not work for writing multiple CSV in for loop


Please look at the pseudocode below:

def main():
    queries = ['A','B','C']
    for query in queries:
        filename = query + '.csv'
        writer = csv.writer(open(filename, 'wt', encoding = 'utf-8'))
        ...
        FUNCTION (query)

def FUNCTION(query):
    ...
    writer.writerow(XXX)

I'd like to write to multiple csv files, so I use for loop to generate different file names, followed by writing into the file in another def()

However, this is not working, the file will be empty.

If I try to get rid of using main() or stop for loop:

writer = csv.writer(open(filename, 'wt', encoding = 'utf-8'))
        ...
FUNCTION (query)
def FUNCTION(query):
       ...
    writer.writerow(XXX)

It'll work.

I don't know why? Anything related to for loop or main()?


Solution

  • A simple fix is to pass the file handle and not the name to FUNCTION. Since the file has been opened in main, you don't need/want the name in the subroutine, just the file handle so change the call to FUNCTION(writer) and the definition to

    def FUNCTION(writer):

    and use writer.writerow(xxx) wherever you need to stream output in the subroutine.

    Note: you changed the name of the file pointer from writer to write in your example.