属性错误:'module'对象没有'mkdirs'属性。

15

在Python 3.6中创建嵌套目录时,收到以下错误:

AttributeError: 'module' object has no attribute 'mkdirs'

示例代码:

def create_sample_data():
    os.mkdirs("/tmp/lambdadir/ProjectTemp/mynewtest")
    f=open("/tmp/lambdadir/ProjectTemp/mynewtest/my_copy.txt","w+")
    f.write("This is inside a directory")
    f.close()
请帮忙。
3个回答

41

哦,这正是我需要的:) - undefined

6

经过一番搜索,发现这是一个Python版本问题。

我将代码从os.mkdirs()更改为os.makedirs(),然后它就起作用了。

详情请见:os模块文档

致谢: buttscicles - Reddit


2
由于您正在使用3.6版本,请考虑使用path.mkdir(parents=True)path.write_text('this is inside a directory')。总的来说,我发现pathlib在任何类型的文件系统操作中都更容易使用。 - Ben
@Ben 除了更明确外,还有其他的功能优势吗? - Kermit
@HashRocketSyntax,使用pathlib编写代码要容易得多。函数中的四行变成了两行 - 可能甚至不需要将其放在一个函数中。下次处理路径/文件/文件夹时,请查看一下pathlib。就我个人而言,我保证你会喜欢它(虽然这可能并不值什么 lol)。 - Ben

0
在3.10版本中,当我尝试时遇到了同样的问题。似乎它不可用,所以我使用了下面的代码。
# The folder should not exist or else will throw FileExistsError
os.mkdir('Parent-folder')
# The parent folder is should be created before , or else throws FileNotFoundError:
os.mkdir('Parent-folder/SubFolder')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接