13

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

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

4

2 回答 2

27

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

那应该行得通。

于 2013-01-02T16:54:10.797 回答
12

需要注意的一件事是(根据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,确保使用了正确的分隔符(请注意上面输出中的差异os.path.join('first_part', 'second_part')。

于 2013-01-02T16:56:14.783 回答