Home > Mobile >  While loop to write in several text files
While loop to write in several text files

Time:12-05

I'm trying to write some lines of text in different text files.

The problem is that I can't close the first one and move to the next one using a while loop.

I want to use a while loop because the number of files that I want to create is undefined, so at the end of each case I want the program to ask me if I have finished working, like this:

status = input('finished? ')

If the answer is YES, I want the program to stop. If the answer is NO, I want the program to continue creating .txt files and printing the information I have specified.

import sys

while True:
    file_txt = str(input('.txt file name? ') '.txt')
    sys.stdout = open(file_txt, "w")

    print('This will be printed in the file')

    sys.stdout.close()

    status = input('finished? ')
    if status == 'yes':
        break
    else:
        continue

The problem with this code is that I'm getting the following error:

ValueError: I/O operation on closed file.

CodePudding user response:

Unclear why you need sys module. Just write to a file object

Specifically, closing the system stream closes it for good

while True:
    file_txt = input('.txt file name? ') '.txt'
    
    with open(file_txt, "w") as f:
        f.write('This will be printed in the file') 
    status = input('finished? ')
    if status == 'yes':
        break

CodePudding user response:

Guess where does input('finished? ') write the text? In the sys.stdout you just closed! Try setting it back to console

sys.stdout = open(file_txt, "w")

print('This will be printed in the file')

sys.stdout.close()
sys.stdout = sys.__stdout__

CodePudding user response:

First of all, unless there's more code at the bottom of the loop, there's no need to continue.

You're trying to write to sys.stdout (standard output) by using print. After closing sys.stdout, you reset it. However, when I run your code (from unix), it seems as though input accesses stdout when you type anything into stdout- even if you haven't typed anything.

  • Related