Python Forum
Saving text file with a click: valueerror i/o operation on closed file
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Saving text file with a click: valueerror i/o operation on closed file
#2
You can redirect sys.stdout by defining your own context. The following code prints 'Hello there!' in file 'foo.txt' and then 'Done' to standard output. Don't close files explicitly when using the 'with' statement. They are closed automatically when the context exits
from contextlib import contextmanager
import sys

@contextmanager
def redirect_stdout(file):
    old, sys.stdout = sys.stdout, file
    try:
        yield
    finally:
        sys.stdout = old

def main():
    with open('foo.txt', 'w') as file, redirect_stdout(file):
        print('Hello there!')
    print('Done')

if __name__ == '__main__':
    main()
That said, I don't know how the HeartRateMonitor class works, but you could consider injecting a file argument in this class instead of redirecting the global stdout.
vizier87 likes this post
Reply


Messages In This Thread
RE: Saving text file with a click: valueerror i/o operation on closed file - by Gribouillis - Nov-12-2020, 04:46 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  [closed] check whether an integer is 32 or 64 bits paul18fr 4 250 May-27-2024, 04:55 PM
Last Post: deanhystad
  How to Randomly Print a Quote From a Text File When User Types a Command on Main Menu BillKochman 13 1,390 Apr-24-2024, 05:47 AM
Last Post: Bronjer
  very newbie problem on text file zapad 2 368 Apr-12-2024, 06:50 PM
Last Post: zapad
  This result object does not return rows. It has been closed automatically dawid294 6 1,531 Mar-30-2024, 03:08 AM
Last Post: NolaCuriel
  file open "file not found error" shanoger 8 1,420 Dec-14-2023, 08:03 AM
Last Post: shanoger
  Replace a text/word in docx file using Python Devan 4 4,140 Oct-17-2023, 06:03 PM
Last Post: Devan
  Need to replace a string with a file (HTML file) tester_V 1 856 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  How can I change the uuid name of a file to his original file? MaddoxMB 2 1,065 Jul-17-2023, 10:15 PM
Last Post: Pedroski55
  save values permanently in python (perhaps not in a text file)? flash77 8 1,382 Jul-07-2023, 05:44 PM
Last Post: flash77
  Reading data from excel file –> process it >>then write to another excel output file Jennifer_Jone 0 1,220 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020