我正在尝试创建一堆目录。其中一些将由于权限等原因而失败,在这种情况下,我希望在/tmp
中创建该目录,然后替换相应变量中的值。
import os
ROOT = "/var"
IMG_DIR = "images"
HASH_DIR = "hashes"
TEAM_DIR = "teams"
for some_dir in [IMG_DIR, HASH_DIR, TEAM_DIR]:
current_path = os.path.join(ROOT, some_dir)
if not os.path.exists(current_path):
try:
os.makedirs(current_path)
except OSError:
new_path = os.path.join("/tmp", some_dir)
# if the error happened in images, update IMG_DIR with the new path
# if the error happened in hashes, update HASH_DIR with the new path
# if the error happened in teams, update TEAM_DIR with the new path
IMG_DIR
,HASH_DIR
和TEAM_DIR
将是全局变量,并且在整个程序中都可以访问。
什么是最优雅/ Pythonic的方法来完成此任务?
答案 0 :(得分:2)
您需要类似的东西:
import os
ROOT = "/var"
my_dirs = {
'IMG_DIR': "images",
'HASH_DIR': "hashes",
'TEAM_DIR': "teams"
}
for name, path in my_dirs.items():
current_path = os.path.join(ROOT, path)
if not os.path.exists(current_path):
try:
os.makedirs(current_path)
except OSError:
new_path = os.path.join("/tmp", path)
my_dirs[name] = new_path
如果您严格要求更新变量并且不接受字典(为什么?),则可以使用以下方法:
import os
def create_dir(root: str, path: str) -> str:
current_path = os.path.join(root, path)
if not os.path.exists(current_path):
try:
os.makedirs(current_path)
except OSError:
new_path = os.path.join("/tmp", path)
# maybe create this directory here?
return new_path
return current_path
ROOT = "/var"
IMG_DIR = create_dir(ROOT, "images")
HASH_DIR = create_dir(ROOT, "hashes")
TEAM_DIR = create_dir(ROOT, "teams")