D
D
danis_20142017-02-05 20:07:31
Python
danis_2014, 2017-02-05 20:07:31

How to correctly specify relative paths to files in Python?

Very often errors get out when working with files. Here are a few of them:

os.listdir(r'png')

#FileNotFoundError: [WinError 3] Системе не удается найти указанный путь: 'png'

The script is launched from under the console. The folder is exactly in the same directory as the executable file. Another strange thing is that when you run it from PyCharm, everything works fine. Here's another example:
sftp.put(r'data.txt', r'/root/vk-ali/data.txt')
sftp.put(r'album1.txt', r'/root/vk-ali/album1.txt')
sftp.put(r'C:\Users\danis\AppData\Local\Programs\Python\Python36-32\Lib\vk_ali\desktop\posts1.txt',  # ошибка
             r'/root/vk-ali/posts1.txt')  # ошибка
sftp.put(r'C:\Users\danis\AppData\Local\Programs\Python\Python36-32\Lib\vk_ali\desktop\posts2.txt',  # ошибка                                             
             r'/root/vk-ali/posts2.txt')  # ошибка
sftp.put(r'album2.txt', r'/root/vk-ali/album2.txt')


#FileNotFoundError: [WinError 2] Системе не удается найти указанный файл 'posts1.txt'

Everything works fine here except for the comment lines. In them, I indicated the full path, because. when specifying relative python, it throws an error. And again, in PyCharm everything started without the full path.
How to correctly specify relative paths to files in Python?
SOLVED:
The problem turned out to be the location of the console, thanks Sayonji

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimonchik, 2017-02-05
@dimonchik2013

study

dir_path = os.path.dirname(os.path.realpath(__file__))
или
dir_path = os.path.dirname(os.path.abspath(os.path.join(os.path.realpath(__file__), os.pardir)))

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question