How to leave the program open in python

Asked

Viewed 703 times

0

I made a program that reads a file but it reads and already closes, how to add a 'Press S to exit' for example and leave the print on the screen for longer? -below is the code

lista=open('item.txt','r')
for linha in lista
 itens=linha.split()
 print('Comprar', itens[0])
 linha=lista.readline()

lista.close()

3 answers

2

To make a code run forever and you dehydrate when the code should use while True:


while True:
    lista=open('item.txt','r')
    for linha in lista
        itens=linha.split()
        print('Comprar', itens[0])
        linha=lista.readline()


    resultado = input("Deseja encerrar, [y/n] ")
    if resultado.upper() == 'Y':
        lista.close()
        break

This way the code keeps running until the user asks to exit, typing y to exit.

  • Cara valeu implementei aqui, but now the code ta giving output only the first line of the file now :/ could help me?

  • Try to remove the list.close() out of the if , leaving it below this line. linha=lista.readline() lista.close()

1

To do this just takes one input emptiness

# insira-o no final do seu código
input('Aperte qualquer tecla para fechar o programa...')

;)

-1

The "r" parameter is for reading, each line that goes through the FOR overriding the first one, try changing to "a" of "appending"

Before:

lista=open('item.txt','r')

Afterward:

lista=open('item.txt','a')

'r#open for Reading (default) 'w' open for writing, truncating Theile first 'x' open for exclusive Creation, failing if the file already exists if it exists 'a' open for writing, appending to the end of the file b 'Binary mode’t 'text mode (default) '+' open a disk file for updating (Reading and writing)

Source: Documentation

  • No, because you’re using FOR to go through each line, if you didn’t have it you could read the whole document with . readlines() but would return you a list.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.