F
F
fandorin_official2019-09-18 21:21:55
Python
fandorin_official, 2019-09-18 21:21:55

How to set the correct relative path to a file in Windows?

For example, there is a script located at the following path:
C:\Users\Administrator\Documents\Example in the ex.py
file A file (plain text file) is called in the script file, which lies at the following path:
C:\Users\Administrator\ Documents\Example\Data in the file data.txt
In the code, the path to the file is relative 'Data/data.txt'.
When you run the script through a normal, native Windows scheduler, the script does not see this file and swears.
How can I correctly specify the relative path to the file so that, regardless
of the location of the absolute script file, I do not need to change the path to the files each time, etc.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Dugin, 2019-09-18
@fandorin_official

You have a Unix path, for Windows change the slash back. But this is a crooked decision.
Better use the generic Path class from the pathlib module , it will work on any OS:

from pathlib import Path

path = Path('Data') / 'data.txt'

But you can do it the old fashioned way, through os.path.join()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question