从变量创建文件路径

从变量创建文件路径

本文介绍了从变量创建文件路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找有关使用变量生成文件路径的最佳方法的一些建议,目前我的代码类似于以下内容:

path = /my/root/directory
for x in list_of_vars:
        if os.path.isdir(path + '/' + x):  # line A
            print(x + ' exists.')
        else:
            os.mkdir(path + '/' + x)       # line B
            print(x + ' created.')

对于如上所示的A和B行,是否有更好的方法来创建文件路径,因为当我深入目录树时,该路径会变得更长?

我设想现有的内置方法将按以下方式使用:

create_path(path, 'in', 'here')

生成格式为/my/root/directory/in/here

的路径

如果没有内置函数,我只写一个.

谢谢您的输入.

解决方案

是的,有这样一个内置函数: os.path.join .

>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'

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/directory
for x in list_of_vars:
        if os.path.isdir(path + '/' + x):  # line A
            print(x + ' exists.')
        else:
            os.mkdir(path + '/' + x)       # line B
            print(x + ' created.')

For lines A and B as shown above, is there a better way to create a file path as this will become longer the deeper I delve into the directory tree?

I envisage an existing built-in method to be used as follows:

create_path(path, 'in', 'here')

producing a path of the form /my/root/directory/in/here

If there is no built in function I will just write myself one.

Thank you for any input.

解决方案

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'

这篇关于从变量创建文件路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 11:27