Create the .txt file in PYTHON if it does not exist

1

The code:

        arquivo = open(input('Nome do arquivo a ser editado:'), 'r')
        texto = arquivo.readlines()
        texto.append(input('Insira o texto:'))
        arquivo = open(input('Nome do arquivo a ser editado:'), 'w')
        arquivo.writelines(texto)
        arquivo.close()

It reads an existing .TXT file that writes what is written inside it. And it adds the text that is inserted, I found this way of doing that requires that it ask for 2x the name of the file. Is there a way I do not have to call the name request 2x?

        File "C:\Users\Americo\Desktop\TESTE\Trabson.py", line 51, in sys_calls
        arquivo = open(input('Nome do arquivo a ser editado:'), 'r')
        FileNotFoundError: [Errno 2] No such file or directory: 'teste.txt'

And also if the file does not exist, how do I create and put the text I want inside telling me that the file was created and did not exist. Another user had put in another doubt the following code snippet:

      if os.path.isfile(diretorio):
      ...
      ficheiro = open(diretorio, "w") # criamos/abrimos o ficheiro
      #.... .... ... operacoes no ficheiro
      ficheiro.close()

Is this applied in this case for txt file commit? The snippet worked for part of my code served for all part of MOVE CREATE DELETE AND RENAME some file or directory.

    
asked by anonymous 06.06.2016 / 03:09

2 answers

4

If you do this you do not need to call twice.

arquivo = open(input('Nome do arquivo a ser editado:'), 'r+')
texto = arquivo.readlines()
texto.append(input('insira o valor'))
arquivo.writelines(texto)
arquivo.close()

Now, if the file you entered does not exist, it can be this way.

try:
    nome_arquivo = input('Nome do arquivo a ser editado:')
    arquivo = open(nome_arquivo, 'r+')
except FileNotFoundError:
    arquivo = open(nome_arquivo, 'w+')
    arquivo.writelines(u'Arquivo criado pois nao existia')
#faca o que quiser
arquivo.close()
    
06.06.2016 / 04:21
2

Maybe you can use append files to resolve this problem. But, making the minimum change in your code, you could put the input into a variable, that is:

    nome_do_arquivo = input('Nome do arquivo a ser editado:')
    arquivo = open(nome_do_arquivo, 'r')
    texto = arquivo.readlines()
    texto.append(input('Insira o texto:'))
    arquivo = open(nome_do_arquivo, 'w')
    arquivo.writelines(texto)
    arquivo.close()

Or you can make the following code:

    arquivo = open(input('Nome do arquivo a ser editado:'), 'r+')
    print(arquivo.readlines()) #Consegue ler
    arquivo.write(input('Insira o texto:')+"\n") #consegue editar
    arquivo.close()

It is important to remember that the file should exist, otherwise check before and create.

    
06.06.2016 / 04:24