How would you create an universal path for opening a file in python? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How would you create an universal path for opening a file in python?

I am working on linux and if I open a file for example "data.txt" I have to include the full path which includes my PC name and USB name and everything. How would I create a short path which would work for all users and OS who try my code?

13th Aug 2020, 2:49 PM
Kevin
Kevin - avatar
7 Answers
+ 7
It is not recommended to use os for filepath handling. use pathlib module instead. here is an exellent tutorial that explains it very well: https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-pathlib/
13th Aug 2020, 5:31 PM
Lothar
Lothar - avatar
+ 5
Mirielle, the difference of using os for handling path and using pathlib is, that pathlib handles the path as an object, that has properties and methods. using os path, it is just a string, and you have to take care, that your handling of this string is conform with the needs of the platform. By using pathlib the platform dependent conditions are handled by the module.
14th Aug 2020, 10:48 AM
Lothar
Lothar - avatar
+ 1
I will check it out soon
13th Aug 2020, 10:50 PM
Kevin
Kevin - avatar
+ 1
Read the read_csv method in the machine learning tutorial.. Good example ....
14th Aug 2020, 10:43 AM
Sanjay Kamath
Sanjay Kamath - avatar
0
you can use os module. os.getcwd() returns your current directory.
13th Aug 2020, 2:57 PM
hamit
0
I can't think of a solution to that. You can probably make a variable containing the path to your home directory. Them from there you can use the os.path.join() method to join paths. Example - import os BASE_DIR = "/home/username" # assume your data.txt file is in /home/username/Documents/text_files, you can do this path_to_data_txt_file = os.path.join(BASE_DIR, "Documents/text_files") with open(path_to_data_txt_file) as file: print(file.read()) Your users only need to do os.path.join(BASE_DIR, path), but the problem here is, they can still see the BASE_DIR.
13th Aug 2020, 3:06 PM
XXX
XXX - avatar
0
How do I instantly find the parent folder of the current file?
13th Aug 2020, 6:18 PM
Kevin
Kevin - avatar