gpt4 book ai didi

python - 如何检查 os.makedirs 的参数?

转载 作者:行者123 更新时间:2023-12-01 04:39:11 25 4
gpt4 key购买 nike

我使用此代码为用户创建文件夹:

work_path = '/tmp/'

os.umask(0000)
for i in user:
if not os.path.exists(work_path + i):
try:
os.makedirs(work_path + i, 0777)

当我设置 work_path = '/tmp/' 时 - 我的代码工作完美。但是当我输入错误 work_path = '/tmp' 时,我没有得到预期的结果 )))

问题:如何检查我的路径是否有反斜杠,或者如何以其他方式创建文件夹?

最佳答案

使用os.path.join :

Join one or more path components intelligently. The return value is the concatenation of path and any members of *paths with exactly one directory separator (os.sep) following each non-empty part except the last, meaning that the result will only end in a separator if the last part is empty. If a component is an absolute path, all previous components are thrown away and joining continues from the absolute path component.

os.makedirs(os.path.join(work_path,i))

因此,在您的代码中加入路径一次,然后使用加入的路径:

for i in user:
pth = os.path.join(work_path, i)
if not os.path.exists(pth):
try:
os.makedirs(pth, 0777)

关于python - 如何检查 os.makedirs 的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31136011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com