我正在寻找有关使用变量生成文件路径的最佳方法的建议,目前我的代码类似于以下内容:
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'
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句