我正在寻找一些关于使用变量生成文件路径的最佳方法的建议,目前我的代码看起来类似于以下内容:
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.')
Run Code Online (Sandbox Code Playgroud)
对于如上所示的A行和B行,有没有更好的方法来创建文件路径,因为这会越深入我深入研究目录树?
我设想现有的内置方法如下使用:
create_path(path, 'in', 'here')
Run Code Online (Sandbox Code Playgroud)
产生一种形式的路径 /my/root/directory/in/here
如果没有内置功能,我会自己写一个.
谢谢你的任何意见.
ken*_*ytm 83
是的,有这样一个内置功能:os.path.join.
>>> import os.path
>>> os.path.join('/my/root/directory', 'in', 'here')
'/my/root/directory/in/here'
Run Code Online (Sandbox Code Playgroud)
nmi*_*els 13
您需要os.path中的path.join()函数.
>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'
Run Code Online (Sandbox Code Playgroud)
这将构建与os.sep(而不是更少的便携式的路径'/'),并更有效地做它(一般)比使用+.
但是,这实际上不会创建路径.为此,你必须做一些像你在问题中所做的事情.你可以这样写:
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)
Run Code Online (Sandbox Code Playgroud)
您还可以使用面向对象的路径pathlib(作为 Python 3.4 的标准库提供):
from pathlib import Path
start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
90223 次 |
| 最近记录: |