I have been given a Project on Python Programming so I wanted to ask you that how can I give relative directory paths to the generated files in Python so that it could be opened in other machines as absolute paths won't work on every PC
Asked
Active
Viewed 47 times
-1
-
I don't understand the question, can you expand please? But working with paths is usually done with https://docs.python.org/library/pathlib.html – Boris Verkhovskiy Oct 30 '19 at 09:30
2 Answers
0
If you have write access to the folder containing your script then you can use something like
import sys, os
if __name__ == '__main__':
myself = sys.argv[0]
else:
myself = __file__
myself = os.path.abspath(myself)
whereami = os.path.dirname(myself)
print(myself)
print(whereami)
datadir = os.path.join(whereami, 'data')
if not os.path.exists(datadir):
os.mkdir(datadir)
datafile = os.path.join(datadir, 'foo.txt')
with open(datafile, 'w') as f:
f.write('Hello, World!\n')
with open(datafile) as f:
print(f.read())
0
In the file that has the script, you want to do something like this:
import os
dirname = os.path.dirname(__file__)
filename = os.path.join(dirname, 'relative/path/to/file/you/want')
This will give you the absolute path to the file you're looking for, irrespective of the machine you are running your code on.
You can also refer these links for more information:
For more specific information, please make your question specific. i.e Please post the code that you have tried along with your inputs and expected outputs.

Karthick Mohanraj
- 1,565
- 2
- 13
- 28
-
[How to Answer](https://stackoverflow.com/help/how-to-answer) strongly recommends only answering well-asked questions. – Andreas Oct 30 '19 at 09:50