Read input data and write read lines to a file

Asked

Viewed 138 times

1

I’m trying to create a program that when I give an entry it will create a list within a file, but when I try to do this it adds my entries in a single line and not one under the other.

There must be a command for it, how can I fix it?

arquivo = open('contas', 'w')
def adicionar():
    while True:
        a = input('\nO que quer adicionar?: ')
        arquivo.write(a)
        if a == '':
            break
adicionar()
arquivo.close

2 answers

3

Just add the line break in the string, by passing it to the method write:

with open('contas', 'w') as arquivo:
    while True:
        a = input('\nO que quer adicionar?: ')
        arquivo.write(a + "\n") # <-- aqui
        if not a:
            break

The "\n" matches the line break. Also note that I used with, that already closes the file automatically at the end of the execution, even if an error occurs.

I also removed the function adicionar, which seems unnecessary here. The way it was done, it can only be called after the file is open, and even then the variable can only be called arquivo - Anyway, if you want a function, or it should receive the file as parameter, and should check if it is open, or else the function should receive the name of the file as parameter and do everything within it (open, write, close). But for a small program like this, which will only do that, I find it an exaggeration to create this function.

Notice also at the end: if not a checks if the string is empty. This is another way to check, since an empty string is considered a false value (falsy value) - read more about this here and here.


Another detail is that this code always adds the line break at the end, for all lines - including the empty string. That is, the file will have two blank lines at the end (one relative to the last non-empty string typed, and another relative to the empty string).

If you want to avoid this, just check if the string is empty before of writing:

with open('contas', 'w') as arquivo:
    while True:
        a = input('\nO que quer adicionar?: ')
        if not a: # se a linha for vazia, sai e não escreve ela no arquivo
            break
        arquivo.write(a + "\n")

Now the file will only have an empty line at the end, referring to the last non-empty string typed. But if you want to delete this line too, then the way is to put everything on a list and put it all together at the end:

lista = []
while True:
    a = input('\nO que quer adicionar?: ')
    if not a:  # se a linha for vazia, sai e não adiciona na lista
        break
    lista.append(a)

with open('contas', 'w') as arquivo:
    arquivo.write("\n".join(lista))

Now I create a list and add only the nonempty strings in it. In the end, I add everything with the method join, using the line break as the "joiner" (which will stay between each element in the list). Thus, the last non-empty string will not have the line break added after it.


Another option is instead of arquivo.write, use the function print, passing the file as a parameter (since the print, for default, adds line break at end):

with open('contas', 'w') as arquivo:
    while True:
        a = input('\nO que quer adicionar?: ')
        print(a, file=arquivo)
        if not a:
            break

1

Try this:

arquivo = open('contas', 'w')
def adicionar():
    while True:
        print("O que quer adicionar?: ")
        a="\n".join(iter(input,""))
        arquivo.write(a)
        if a == '':
            break
adicionar()
arquivo.close

I recommend reading:

  1. Iterators in Python
  2. Python String Join()(In English)

Browser other questions tagged

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