Skip to content
Advertisement

How to avoid rewriting filepaths when running a python script on a different computer?

I wrote a script in Jupyter Notebook and the script is using a series of files. I want to send this script and run it on a different computer. Is there any way to avoid having to rewrite each individual filepath when running tje script on the different computer?

# open an existing document
doc = docx.Document(r"C:Userscristword_automationSummary_templateTableTwo.docx") 

Advertisement

Answer

You should checkout os module in Python. This module has various methods which may help you. For instance,

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

If you keep this in your code, BASE_DIR will now have your script location. From this point on you can navigate using relative paths. Once you have the root project folder, you may make use of os.path.join to move around. Here is the Python reference to os module, Python os module

Hope this helps. Feel free to connect if the issue still persists.

Thanks.

Advertisement