How to open . txt files in Python?

Asked

Viewed 4,236 times

1

I want to open a. txt file for reading but python always gives error, want to use

f = open('ficheiro.txt', "r")

or

f =open('C:\...(diretório)...\ficheiro.txt', "r")

I’ve already created files from python to know where they are stored and put the file I want there, and it still doesn’t work. It only works when I copy the content I want to the file I create with python, but it’s a lot of work.

Python always raises this error:

IOError: [Errno 2] No such file or directory: 'ficheiro.txt'

What can I do to solve the problem?

  • The ideal would be that Voce put the real code (Ctrl-c, Ctrl-v) and the error message in the body of your question, the way you wrote it was very comprehensive, difficult to understand what the problem is.

3 answers

2

Hugo, this error is due to Python not locating the file in the location where you are trying to open it. Hence, the file is not in the same location where you are running the script. For example, if your Python script is at the root of the C drive, the file . txt should be there too if its path is not specified.

1

To flag "r" error if the file does not exist.

To avoid error, use "a+":

f = open('ficheiro.txt', "a+")

See more here.

  • But it wants to open the file for reading, if it does not find the file to open, even if it does not present the error, it will not be able to do what it needs since it will not have access to the contents of the file.

  • This is the business of the programmer.

  • Dude, read only... The guy just wants to read what’s in the file, the only goal in opening is to read its content. Kkk

  • Ué, if the answer is not good, you can answer too. It’s better than standing here arguing.

  • They answered right up there

0

I can open the file from anywhere and show it on screen in this way:

f=open("C:\Users\usuario\Downloads\Telefones.txt",'r') #caminho do arquivo
file_data = f.read() #variavel que receberá o arquivo escolhido
print file_data

Browser other questions tagged

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