Create file path from variables

后端 未结 3 1010
忘了有多久
忘了有多久 2020-12-25 10:23

I am looking for some advice as to the best way to generate a file path using variables, currently my code looks similar to the following:

path = /my/root/di         


        
相关标签:
3条回答
  • 2020-12-25 10:28

    You can also use an object-oriented path with pathlib (available as a standard library as of Python 3.4):

    from pathlib import Path
    
    start_path = Path('/my/root/directory')
    final_path = start_path / 'in' / 'here'
    
    0 讨论(0)
  • 2020-12-25 10:34

    Yes there is such a built-in function: os.path.join.

    >>> import os.path
    >>> os.path.join('/my/root/directory', 'in', 'here')
    '/my/root/directory/in/here'
    
    0 讨论(0)
  • 2020-12-25 10:35

    You want the path.join() function from os.path.

    >>> from os import path
    >>> path.join('foo', 'bar')
    'foo/bar'
    

    This builds your path with os.sep (instead of the less portable '/') and does it more efficiently (in general) than using +.

    However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:

    start_path = '/my/root/directory'
    final_path = os.join(start_path, *list_of_vars)
    if not os.path.isdir(final_path):
        os.makedirs (final_path)
    
    0 讨论(0)
提交回复
热议问题