Relative paths in Python

前端 未结 15 1788
陌清茗
陌清茗 2020-11-22 07:39

I\'m building a simple helper script for work that will copy a couple of template files in our code base to the current directory. I don\'t, however, have the absolute path

15条回答
  •  独厮守ぢ
    2020-11-22 08:13

    From what suggest others and from pathlib documentation, a simple and clear solution is the following (suppose the file we need to refer to: Test/data/users.csv:

    # This file location: Tests/src/long/module/subdir/some_script.py
    from pathlib import Path
    
    # back to Tests/
    PROJECT_ROOT = Path(__file__).parents[4]
    # then down to Test/data/users.csv
    CSV_USERS_PATH = PROJECT_ROOT / 'data' / 'users.csv'  
    
    with CSV_USERS_PATH.open() as users:
        print(users.read())
    

    Now this looks a bit odd to me, because if you move some_script.py around, the path to the root of our project may change (we would need to modify parents[4]). On the other hand I found a solution that I prefer based on the same idea.

    Suppose we have the following directory structure:

    Tests
    ├── data
    │  └── users.csv
    └── src
       ├── long
       │  └── module
       │     └── subdir
       │        └── some_script.py
       ├── main.py
       └── paths.py
    

    The paths.py file will be responsible for storing the root location of our projet:

    from pathlib import Path
    
    PROJECT_ROOT = Path(__file__).parents[1]
    

    All scripts can now use paths.PROJECT_ROOT to express absolute paths from the root of the project. For example in src/long/module/subdir/some_script.py we could have:

    from paths import PROJECT_ROOT
    
    CSV_USERS_PATH = PROJECT_ROOT / 'data' / 'users.csv'
    
    def hello():
        with CSV_USERS_PATH.open() as f:
            print(f.read())
    

    And everything goes as expected:

    ~/Tests/src/$ python main.py
    
    /Users/cglacet/Tests/data/users.csv
    hello, user
    
    ~/Tests/$ python src/main.py
    
    /Users/cglacet/Tests/data/users.csv
    hello, user
    

    The main.py script simply is:

    from long.module.subdir import some_script
    
    some_script.hello()
    

提交回复
热议问题