在当前目录中创建的新文件夹

f.a*_*uri 6 python operating-system python-2.7

我有一个Python程序,在进程中它创建了一些文件.我希望程序识别当前目录,然后在目录中创建一个文件夹,以便将创建的文件放在该目录中.

我试过这个:

current_directory = os.getcwd()
final_directory = os.path.join(current_directory, r'/new_folder')
if not os.path.exists(final_directory):
    os.makedirs(final_directory)
Run Code Online (Sandbox Code Playgroud)

但它没有给我我想要的东西.似乎第二行不能按我的意愿工作.有人可以帮我解决问题吗?

het*_*sch 12

认为问题在于r'/new_folder'和它中使用的斜杠(指的是根目录).

尝试使用:

current_directory = os.getcwd()
final_directory = os.path.join(current_directory, r'new_folder')
if not os.path.exists(final_directory):
   os.makedirs(final_directory)
Run Code Online (Sandbox Code Playgroud)

这应该工作.


Roc*_*key 9

需要注意的一点是(根据os.path.join文档)如果提供绝对路径作为参数之一,则其他元素将被丢弃.例如(在Linux上):

In [1]: import os.path

In [2]: os.path.join('first_part', 'second_part')
Out[2]: 'first_part/second_part'

In [3]: os.path.join('first_part', r'/second_part')
Out[3]: '/second_part'
Run Code Online (Sandbox Code Playgroud)

在Windows上:

>>> import os.path
>>> os.path.join('first_part', 'second_part')
'first_part\\second_part'
>>> os.path.join('first_part', '/second_part')
'/second_part'
Run Code Online (Sandbox Code Playgroud)

由于/join参数中包含一个前导,因此它被解释为绝对路径,因此忽略其余部分.因此,您应该/从第二个参数的开头删除,以使连接按预期执行.您不必包含的/原因是因为os.path.join隐式使用os.sep,确保使用正确的分隔符(请注意上面输出中的差异os.path.join('first_part', 'second_part').