简体   繁体   中英

Running python codes from outside the directory when script has filepaths

So I have a python script my_script.py which is inside the folder Test and I am outside this folder. The script requires to access some input data from the file my_data.dat stored inside the folder Test .

Now, when I try to run this script from outside the folder Test , using simple python my_script.py , it tries to locate my_data.dat in the folder from which I am running the script and so fails. How can I tell it use the correct path without actually modifying the path in the my_script.py?

I don't want to modify the paths in the script because the script is to be used generically for various paths and the whole thing would be automated later.

You need to use absolute file path instead of the relative file path.

To get absolute path of directory containing python file:

import os
ROOT_DIR = os.path.dirname(__file__)

And you can get absolute path of my_data.dat

data_file_path = os.path.join(ROOT_DIR, 'my_data.dat')

Afterward use data_file_path instead of "my_data.dat"

您可以将路径my_data.dat作为脚本的参数传递,或者(如果数据文件始终与脚本位于同一目录中),则可以使用变量__file__来确定脚本的位置并查找数据该目录中的文件。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM