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

2024-04-28 09:31:05 发布

您现在位置:Python中文网/ 问答频道 /正文

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

但它没有给我想要的。似乎第二条线没有按我的要求工作。有谁能帮我解决这个问题吗?


Tags: 文件path程序目录文件夹newifos
2条回答

需要注意的一点是(根据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参数中包含前导/,因此它被解释为绝对路径,因此忽略其余路径。因此,您应该从第二个参数的开头删除/,以便让join按预期执行。不必包含/的原因是os.path.join隐式使用os.sep,确保使用了正确的分隔符(注意上面的os.path.join('first_part', 'second_part'输出中的差异)。

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

这应该管用。

相关问题 更多 >