Python os module op...
 
Share:
Notifications
Clear all

Python os module open file above current directory with relative path.


Neha
 Neha
(@asha)
Member Admin
Joined: 4 years ago
Posts: 31
Topic starter  

How can I use the current directory or script's directory as a relative path in Python scipting?


Quote
Topic Tags
myTechMint
(@mytechmint)
Member Moderator
Joined: 4 years ago
Posts: 52
 

The path given to open should be relative to the current working directory, the directory from which you run the script. So the above example will only work if you run it from the cgi-bin directory.
A simple solution would be to make your path relative to the script. One possible solution.

from os import path
basepath = path.dirname(__file__)
filepath = path.abspath(path.join(basepath, "..", "..", "fileIwantToOpen.txt"))
f = open(filepath, "r")

This way you'll get the path of the script you're running (basepath) and join that with the relative path of the file you want to open. os.path will take care of the details of joining the two paths.


Neha liked
ReplyQuote