E
E
Evgeny Kolesov2018-04-13 12:11:10
Python
Evgeny Kolesov, 2018-04-13 12:11:10

How to correctly set the path to a file in python?

I know this is a stupid question, but always, open a file like this: cd Desktop and the next command was python3 (filename with extension .py)
started going through the topic of files where you can open, like
F = open('filename with extension'), what does he give me

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: 'kl.py'

those. there is no such file.
Question, even two. 1. Why do you need to constantly set the path to the file, when in any video lesson or book it opens the file by default without this error? And the 2nd question is how to correctly set the path to the file in the F = open("") command without resorting to clumsy cd?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
Stanislav Pugachev, 2018-04-13
@jaimekoyl

how to correctly set the path to the file in the command F = open("") without resorting to clumsy cd?

something like this
with open(os.path.join('Desktop', 'kl.py')) as f:
    pass

A
Anatoly, 2018-04-13
@trofimovdev

structure
C:\Desktop\project
├── abc.txt
├── main.py
├── folder
    └── xyz.txt

Specify an absolute path: C:\Desktop\project\abc.txt, C:\Desktop\project\folder\xyz.txt,
or
specify a relative path: abc.txt, folder\xyz.txt
PS: why open a .py file? You can write import file instead :)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question