E
E
Evgeny Kolesov2018-04-13 14:04:20
Python
Evgeny Kolesov, 2018-04-13 14:04:20

Why can't I open a file in python?

Gentlemen, or I'm stupid or the skis don't go, as they say. What am I doing wrong?
Mark Lutz's book has a section on working with files. So here's to the point. There is a source code
myfile = open('myfile.txt'. 'w')
. In addition to the command, I also set the address. For some reason, Linux does not allow me to throw all the files into the folder with the python, and I want to run them from the desktop. So my code looks like this

> myfile = open('home\usr\bin\Desktop\myfile.txt'. 'w')

what gives me this
File "<stdin>", line 1
SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 4-5: truncated \uXXXX escape

ps I'm on Ubuntu/
The question is, what am I doing wrong? Where is the mistake?
pss in Idle3 produces just such a slash, I tried to make a backslash, I was given a standard
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'home/usr/bin/Desktop/myfile.txt.w
Although the file itself exists.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anatoly, 2018-04-13
@jaimekoyl

In addition to answer

javedimka
open(r'home\usr\bin\Desktop\myfile.txt', 'w')

You need to specify the prefix r , because you are using a backslash in the file path.
"Normal" strings in Python use a backslash to escape special characters (e.g. \n - line break). The r prefix tells the interpreter not to do this:
print('Hello, \n World!')
>> Hello, 
 World!

print(r'Hello, \n World!')
>> Hello, \n World!

I also strongly advise you to use the "correct slash ( / ) if you are not on Windows (that is, the path will be /home/usr/bin/Desktop/myfile.txt)
You have an error in that you specify a relative path (without / at the beginning), although it is clear from your path that you wanted to specify an absolute path (more about the difference between them here ).

E
Evgeny Kolesov, 2018-04-13
@jaimekoyl

Stanislav Pugachev , yes, it happened, I saw it now. So I'm just pointing the wrong way, right?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question