ValueError: I/O operation on closed file while trying to write a value to a .txt file

I want to write a money tracker in python using Tkinter. The way I want it to work is there will be a Label that says how much money I currently have (it reads from a .txt file), two buttons "add" and "subtract" that add or subtract the value written in an Entry from the money amount (it erases the previous amount from the .txt file and writes a new one). I was writing the add_value() function when I encountered this error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Гриша\AppData\Local\Programs\Python\Python38\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:/Users/Гриша/PycharmProjects/untitled1/money tracker.py", line 24, in add_value
    f.write(str(new_amt))
ValueError: I/O operation on closed file.

Here's the function:

def add_value():
    global value_entry
    global money_lbl
    # Gets the number that was stored previously
    with open('money.txt', 'r') as f:
        amt = f.readline()
    # This should erase the contents of the 'money.txt' file
    with open('money.txt', 'w'):
        pass
    # Writing the new value to the file
    with open('money.txt', 'w+'):
        new_amt = int(amt) + int(value_entry.get())
        f.write(str(new_amt))
        money_lbl.configure(text=str(new_amt))

Sorry if I overexplained or if I made some mistakes English is a second language)

Upvotes: 0

Views: 53

Answers (1)

karlson
karlson

Reputation: 5433

You are referencing f outside of the with-block for which it is defined. f is only referencing an open file inside your first with-block (and even there it's opened in read-only mode). Specifically you're missing the as f part in your last context:

with open('money.txt', 'w+') as f:
    new_amt = ...

There are other issues with your code, though. E.g. the second with-block shouldn't be necessary. Just open your file in mode "w" directly. The use of global variables is highly discouraged and int(amt) is not guaranteed to succeed.

Upvotes: 1

Related Questions