This will return the exception “ValueError: I/O operation on closed file”
JavaScript
x
19
19
1
def clear():
2
os.system('cls')
3
def openFile(operation):
4
global file
5
global writer
6
with open(r'C:\Users\UserDocuments\Proxy Database\Proxy.csv',operation, newline= '') as file:
7
writer = csv.writer(file)
8
while True:
9
dir = input('Enter Operation > ')
10
if dir == 'add':
11
openFile("a")
12
print('! Adding User !')
13
name = input('Enter Name > ')
14
writer.writerow([name])
15
print('User Added')
16
file.flush()
17
clear()
18
continue
19
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.
JavaScript
1
13
13
1
with open(r'C:\Users\riccoDocuments\Proxy Database\Proxy.csv','r+', newline= '') as file:
2
writer = csv.writer(file)
3
while True:
4
dir = input('Enter Operation > ')
5
if dir == 'add':
6
print('! Adding User !')
7
name = input('Enter Name > ')
8
writer.writerow([name])
9
print('User Added')
10
file.flush()
11
break
12
print('Done')
13
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:
JavaScript
1
10
10
1
def openFile(operation):
2
3
handle = open(r'C:\Users\UserDocuments\Proxy Database\Proxy.csv',operation, newline= '')
4
writer = csv.writer(handle)
5
return writer
6
7
8
writer = openFile("a")
9
10