Absolute vs. Relative File Path (Python)

208 Views Asked by At

Is it better to use a relative or absolute file path in Python, in both a situational setting and for best practice?

I know what both of them do, and I'm wondering if, for example, always using an absolute file path is better practice than using a relative file path, or if it depends.

And if it is a situational thing, when should you use one or the other?

2

There are 2 best solutions below

0
Abhishek Dutta On BEST ANSWER

For best practice, I would strongly suggest relative paths. Especially if you're going to distribute your Python project across different systems.

The core problem with the absolute path is that it'll break the code if someone else tries to run the code containing your or the original author's absolute path.

Pathlib can help you with paths in general.

0
albenjarvis On

When you ensure that your program runs locally and the absolute path will not change in any way, you can choose to use the absolute path. If you want to port the program to different computers or operating systems, you can choose to use relative paths to avoid modifying the path and file location on the host.