我可以使用os.mkdir()在运行时创建具有动态名称的目录吗?

Aru*_*hit 3 python python-2.7

我必须通过几个请求从网上下载文件.每个请求的下载文件必须放在与请求编号同名的文件夹中.

例如:

我的脚本现在正在运行以下载请求号为87665的文件.因此所有下载的文件都将放在目标文件夹中Current Download\Attachment87665.那我该怎么做?

到目前为止我尝试了什么:

my_dir = "D:\Current Download"
my_dir = os.path.expanduser(my_dir)
if not os.path.exists(my_dir):
    os.makedirs(my_dir)
Run Code Online (Sandbox Code Playgroud)

但它不符合我原来的要求.知道怎么做到这一点?

mik*_*iku 6

只需通过os.path.join以下方式创建路径:

request_number = 82673

# base dir
_dir = "D:\Current Download"       

# create dynamic name, like "D:\Current Download\Attachment82673"
_dir = os.path.join(_dir, 'Attachment%s' % request_number)

# create 'dynamic' dir, if it does not exist
if not os.path.exists(_dir):
    os.makedirs(_dir)
Run Code Online (Sandbox Code Playgroud)