B
B
BUKUBAKA2016-10-28 17:18:31
Python
BUKUBAKA, 2016-10-28 17:18:31

When trying to read the file, an error occurs: there is no such file or directory. Python version 3.5.2. How to make it work properly?

filename = r'''C:\Users\Python\Python35-32\lessons\charper_7\exp_1_read_text_from_file\charper_7\test.txt'''
try:
    text_file = open( filename, "r", encoding = 'utf-8')
    print(text_file.read(2))
except OSError as f:
    print('ERROR: ',f)

Answer the question

In order to leave comments, you need to log in

6 answer(s)
F
Fractal Zombie, 2016-10-28
@FractalZombie

Why you are not using relative path: That in translation use relative paths. I think the problem is somewhere in this.

path = '/Users/Fractal/Desktop/file.txt'

try:
    file = open(path)
except OSError as e:
    pass

I strongly recommend using a Unix system.

S
sim3x, 2016-10-28
@sim3x

filename = r'C:\Users\Python\Python35-32\lessons\charper_7\exp_1_read_text_from_file\charper_7\test.txt'
with open( filename, "r", encoding = 'utf-8') as text_file:
    print(text_file.read(2))

A
Andy_U, 2016-10-29
@Andy_U

And if you change the word charper_7 to chapter_7, won't it get better? And, of course, remove the extra quotes - leave one at the beginning after 'r' and one at the end. And the second occurrence of charper_7 (chapter_7) is not superfluous?

M
Mikhail Malakhov, 2016-10-29
@MalahovMV

I haven’t written on Windows for a long time, try to register a double slash everywhere on the way.

B
BUKUBAKA, 2016-10-31
@BUKUBAKA

found the answer!
The problem was that I called the file test.txt, and the python .txt extension I wrote did not count as an extension. Therefore, it is correct to write: test.txt.txt and everything works.
Thanks to everyone who tried to help

D
dmitry_sh, 2018-03-07
@dmitry_sh

I also encountered this on Windows 10 in the console . I solved it only when I moved from relative paths (which I used in the iPython laptop and in the debugger on Spyder) to absolute paths

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question