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?
7 Respuestas
+ 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/
+ 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.
+ 1
I will check it out soon
+ 1
Read the read_csv method in the machine learning tutorial..
Good example ....
0
you can use os module.
os.getcwd() returns your current directory.
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.
0
How do I instantly find the parent folder of the current file?