Declaring CSV write globally

Question:

I have a script, but broken down it looks like this

import csv
#Global
writervariable = ''

def function1(): <--uses the writervariable.writerow
def function2():
def main():
    writervariable = csv.writer(file)
    function1()
    function2()
main()

I am getting the error str has no writerow method, which make sense, but I thought setting it to csv.writer would change its type.

When I was just prototyping my script, I did this all in one big chaos function, and it worked.

Adding minimal reproducible example:

import csv

writer = ''

def function1():
    writer.writerow(['data1', 'data2'])

def main():
    with open('TestFile', 'w', newline='') as file:
        writer = csv.writer(file)
        writer.writerow(['header1', 'header2'])
        function1()

main()
Asked By: BlueBaroo

||

Answers:

You get the error because you actually have 2 writervariables in 2 different scopes. One is a string in the global scope, and another one – a csv.writer in the scope of the main() function.

When you try to call writervariable.writerow() inside the function1(), this function can "see" the writervariable in the global scope, which is a string, but the scope of the main function is out of visibility.

What you want to do is to pass the writervariable from the main() function to function1() and then use it there:

def function1(csv_writer): <--uses the writervariable.writerow
    csv_writer.writerow()
def function2():
def main():
    writervariable = csv.writer(file)
    function1(writervariable)
    function2()
main()
Answered By: wombatonfire
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.