python - What is the best practice for working with files and paths? -


i creating python script takes 'path file' argument user. post processing , creates new file in same directory original file.

for example: myscript.py c:\\a\\sub_a\\work_on_this_file.csv

i'm using path received create file handler for
c:\\a\\sub_a\\final_file.csv

i've been told use os.chdir() navigate folder instead , create final file there instead of using paths directly. best practice in such scenario? there risk in not changing working directory?

i encourage always use absolute paths, in practice that's straightforward way. so, directly creating file (or opening existing one, doesn't matter) using absolute path fine.

when not sure whether have absolute or relative path woul suggest taking script's directory base folder , generating absolute path, so:

import os  cwd = os.path.abspath(os.path.dirname(__file__)) given_path = "../../myfile.csv" csv_path = os.path.abspath(os.path.join(cwd, given_path)) 

instead of __file__ use sys.argv[0] when dealing modules/imported scripts. imo changing cwd not required , break other things or later.


Comments

Popular posts from this blog

python Tkinter Capturing keyboard events save as one single string -

android - InAppBilling registering BroadcastReceiver in AndroidManifest -

javascript - Z-index in d3.js -