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
#4
For the first question, you still have the error because you must not indent the
@contextmanager
def redirect_stdout(file):
    ...
Don't write this definition in a class, write it at module level outside of any class and without indentation.

If you want to print simultaneously to the file and to the console, here is an updated version
from contextlib import contextmanager
import sys

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

class FileTee:
    """Stores a sequence of file objects to allow printing to several files at a time"""
    def __init__(self, ifile):
        self.ifile = list(ifile)
        
    def write(self, s):
        for f in self.ifile:
            f.write(s)

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

if __name__ == '__main__':
    main()
Reply


Messages In This Thread
RE: Saving text file with a click: valueerror i/o operation on closed file - by Gribouillis - Nov-13-2020, 09:40 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How to Randomly Print a Quote From a Text File When User Types a Command on Main Menu BillKochman 13 1,100 Apr-24-2024, 05:47 AM
Last Post: Bronjer
  very newbie problem on text file zapad 2 285 Apr-12-2024, 06:50 PM
Last Post: zapad
  This result object does not return rows. It has been closed automatically dawid294 6 1,261 Mar-30-2024, 03:08 AM
Last Post: NolaCuriel
  file open "file not found error" shanoger 8 1,271 Dec-14-2023, 08:03 AM
Last Post: shanoger
  Replace a text/word in docx file using Python Devan 4 3,704 Oct-17-2023, 06:03 PM
Last Post: Devan
  Need to replace a string with a file (HTML file) tester_V 1 800 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 991 Jul-17-2023, 10:15 PM
Last Post: Pedroski55
  save values permanently in python (perhaps not in a text file)? flash77 8 1,285 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,155 Mar-14-2023, 07:59 PM
Last Post: Jennifer_Jone
  Read text file, modify it then write back Pavel_47 5 1,697 Feb-18-2023, 02:49 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

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