Sjn73 Sjn73 - 3 months ago 19
Python Question

Accessing global file in the user defined function

I am trying to access file which is opened globally as below:

with open("number.txt") as num:

will be having some number
After the above lines of code if I use the above file pointer inside a method as below:

def updateval():
global num

I am getting error as :
ValueError: I/O operation on closed file

If I open file inside function then there wont be any issue.But I want to open file only once so in many opther function I can perform file operation without opening again and again

Please help me in resolving this!!
Many thanks in advance..

Answer Source

You have two problems:

  1. with closes the file when the enclosing code block exists.
  2. You open the file for reading, so even if you don't close the file, you can't write to it.

Solution 1:

with open('number.txt') as num:  # opens for read-only by default
    val = int(
# file is closed here

def updateval(numb):
    with output('number.txt','w') as num:  # re-opened for writing
    # file is closed here

Solution 2 (if you really want to open the file once):

num = open('number.txt','r+')
val = int(

def updateval(numb):
    # You don't need "global" when you mutate an object,
    # only for new assignment, e.g. num = open(...)           # 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download