【问题标题】:New folder that is created inside the current directory在当前目录中创建的新文件夹
【发布时间】:2012-12-17 00:58:11
【问题描述】:

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

但它并没有给我想要的东西。似乎第二行没有按我的意愿工作。谁能帮我解决这个问题?

【问题讨论】:

  • 但它并没有给我想要的东西:始终明确它做了什么。
  • print ">" % final_directory 的输出是什么?

标签: python python-2.7 operating-system


【解决方案1】:

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

应该可以的。

【讨论】:

  • 查看@RocketDonkey 更好的解释了解更多信息。
  • 谢谢,你赢了! :-)
  • @hetch 这里的if语句有什么用?
  • @AdnanAkram 检查文件夹“new_folder”是否已经存在。如果存在,则不会再次创建目录
【解决方案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 参数中包含前导 /,它被解释为绝对路径,因此忽略其余部分。因此,您应该从第二个参数的开头删除/,以使连接按预期执行。您不必包含/ 的原因是因为os.path.join 隐式使用os.sep,确保使用了正确的分隔符(注意上面输出中os.path.join('first_part', 'second_part' 的差异)。

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 2021-12-05
    • 2017-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多