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

时间:2013-01-02 16:45:52

标签: python python-2.7 operating-system

我有一个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)

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

2 个答案:

答案 0 :(得分:11)

认为问题出在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)

这应该有效。

答案 1 :(得分:8)

需要注意的一点是(根据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'

在Windows上:

>>> import os.path
>>> os.path.join('first_part', 'second_part')
'first_part\\second_part'
>>> os.path.join('first_part', '/second_part')
'/second_part'

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

相关问题