How to open .txt files in Python?

0

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

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

or

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

I have already created files from python to know where they are stored and put there the file I want, and it still does not work. It only gives when I copy the content I want to the file I create with python, but it gives 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?

    
asked by anonymous 30.04.2017 / 17:48

3 answers

2

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

    
01.05.2017 / 22:05
0

The flag "r" gives error if the file does not exist.

To avoid the error, use "a+" :

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

See more here .

    
01.05.2017 / 22:19
0

I can open the file from anywhere and display it on the screen 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
    
29.01.2018 / 23:58