在当前目录内创建的新文件夹 [英] New folder that is created inside the current directory

查看:209
本文介绍了在当前目录内创建的新文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a program in Python that during the processes it creates some files. I want the program to recognize the current directory and then then creates a folder inside the directory, so that the created files will be put in that directory.

我尝试过:

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)

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

But it doesn't give me what I wanted. It seems that the second line is not working as I wanted. Can anybody help me to solve the problem?

推荐答案

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

One thing to note is that (per the os.path.join documentation) if an absolute path is provided as one of the arguments, the other elements are thrown away. For instance (on 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'而言是不同的).

Since you include a leading / in your join argument, it is being interpreted as an absolute path and therefore ignoring the rest. Therefore you should remove the / from the beginning of the second argument in order to have the join perform as expected. The reason you don't have to include the / is because os.path.join implicitly uses os.sep, ensuring that the proper separator is used (note the difference in the output above for os.path.join('first_part', 'second_part').

这篇关于在当前目录内创建的新文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆