Code:
import os
script_path = os.path.abspath(__file__)
path_list = script_path.split(os.sep)
script_directory = path_list[0:len(path_list)-1]
rel_path = "main/2091/data.txt"
path = "/".join(script_directory) + "/" + rel_path
Explanation:
Import library:
import os
Use __file__
to attain the current script's path:
script_path = os.path.abspath(__file__)
Separates the script path into multiple items:
path_list = script_path.split(os.sep)
Remove the last item in the list (the actual script file):
script_directory = path_list[0:len(path_list)-1]
Add the relative file's path:
rel_path = "main/2091/data.txt
Join the list items, and addition the relative path's file:
path = "/".join(script_directory) + "/" + rel_path
Now you are set to do whatever you want with the file, such as, for example:
file = open(path)
r"\2091\sample.txt"
. Or escape them like"\\2091\\sample.txt"
(but that is annoying). Also, 2) you are using getcwd() which is the path you were in when you execute the script. I thought you wanted relative to the script location (but now am wondering). And 3), always useos.path
functions for manipulating paths. Your path joining line should beos.path.join(os.getcwd(), file)
4) the ; is pointless – Tarratarradiddlewith open(path, 'r+') as fp:
. See here for the best explanation ofwith
statements I've seen. – Tarratarradiddleos.path.abspath
to get easly the full path of the relative path to open. final statement looks like this:os.path.abspath('./2091/sample.txt')
– Lucrative