python - How to indicate the current directory of the script not me? -
this question has answer here:
- find current directory , file's directory 15 answers
i have python script reads input file supposed in same directory of script:
with open('./input1.txt') file: f = file.readlines() do_stuff(f)
i run script other directories (not directory script , input files reside), raises ioerror can't find input file (as not in current working directory). don't prefer putting full path input file since want portable- both script , input files have in same directory.
is there way indicate script in location directory not directory launching from?
__file__
path of script, albeit relative path. use:
import os.path scriptdir = os.path.dirname(os.path.abspath(__file__))
to create absolute path directory, use os.path.join()
open file:
with open(os.path.join(scriptdir, './input1.txt')) openfile:
Comments
Post a Comment