Python 从变量创建文件路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3751900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create file path from variables
提问by Thorsley
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?
对于如上所示的 A 行和 B 行,是否有更好的方法来创建文件路径,因为我越深入研究目录树,路径就会变得越长?
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
生成表单的路径 /my/root/directory/in/here
If there is no built in function I will just write myself one.
如果没有内置函数,我就自己写一个。
Thank you for any input.
感谢您提供任何意见。
采纳答案by kennytm
Yes there is such a built-in function: os.path.join.
是的,有这样一个内置函数:os.path.join.
>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'
回答by nmichaels
You want the path.join() function from os.path.
您需要 os.path 中的 path.join() 函数。
>>> 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 +.
这会使用 os.sep (而不是不太便携的'/')构建您的路径,并且比使用.sep更有效(通常)+。
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)

