Skip to content
Advertisement

Can’t write to CSV in function

This will return the exception “ValueError: I/O operation on closed file”

def clear():
    os.system('cls')
def openFile(operation):
    global file
    global writer
    with open(r'C:\Users\UserDocuments\Proxy Database\Proxy.csv',operation, newline= '') as file:
        writer = csv.writer(file)
while True:
    dir = input('Enter Operation > ')
    if dir == 'add':
        openFile("a")
        print('! Adding User !')
        name = input('Enter Name > ')
        writer.writerow([name])
        print('User Added')
        file.flush()
        clear()
        continue

I notice that when I put all the code under the initial CSV Open everything works fine, it just dosen’t work when put into a function.

with open(r'C:\Users\riccoDocuments\Proxy Database\Proxy.csv','r+', newline= '') as file:
        writer = csv.writer(file)
        while True:
            dir = input('Enter Operation > ')
            if dir == 'add':
                print('! Adding User !')
                name = input('Enter Name > ')
                writer.writerow([name])
                print('User Added')
                file.flush()
                break
        print('Done')

Advertisement

Answer

It doesn’t work, because you did not put all of the pertinent code into the function. You open the file in a with block inside your function. Then you exit the block (which closes the file), return from the function, and then your main program attempts to write to the closed file … hence the error message.

If you want to open the file in the function, but write to it in the calling routine, then you need a normal open, and have the function return the needed information. For instance:

def openFile(operation):

    handle = open(r'C:\Users\UserDocuments\Proxy Database\Proxy.csv',operation, newline= '')
    writer = csv.writer(handle)
    return writer

...
writer = openFile("a")
...
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement