I am trying to access file which is opened globally as below:
with open("number.txt") as num:
val=int(num.read())
number.txt
def updateval():
global num
num.write(numb)
ValueError: I/O operation on closed file
You have two problems:
with
closes the file when the enclosing code block exists.Solution 1:
with open('number.txt') as num: # opens for read-only by default
val = int(num.read())
# file is closed here
def updateval(numb):
with output('number.txt','w') as num: # re-opened for writing
num.write(numb)
# file is closed here
Solution 2 (if you really want to open the file once):
num = open('number.txt','r+')
val = int(num.read())
def updateval(numb):
# You don't need "global" when you mutate an object,
# only for new assignment, e.g. num = open(...)
num.seek(0) # make sure to write at the beginning of the file.
num.truncate() # erase the current content.
num.write(str(numb)) # write the number as a string
num.flush() # make sure to flush it to disk.
Obviously, the second solution you have to micromanage what you are doing. Use solution 1.