首页 > 解决方案 > os python模块使其他代码无法正常工作

问题描述

我正在制作一个需要一种方法来创建文件夹的程序,但我发现的唯一方法是操作系统模块。但是,它会混淆保存和写入文件的代码。例子:

import os

# necessary code that creates folder
os.chdir("Example_directory/")
os.mkdir("New_folder_name")

# necessary code that writes to a text file
file = open("File_directory/document.txt", "w")
file.write("Text sample")
file.close()

错误信息是:

  File "C:\Users\First Name Last Name\Desktop\sample\main.py", line 8, in <module>
    file = open("File_directory/document.txt", "w")
FileNotFoundError: [Errno 2] No such file or directory: 'File_directory/document.txt' 

即使该目录确实存在。并且为了证明 os 模块是搞乱代码的东西,当我删除 os 模块及其代码块时,我没有收到任何错误。

我的主要观点是:有人知道在 python 中创建文件夹的另一种方法吗?

标签: python

解决方案


File_directory大概存在于进程的原始工作目录中。但是你用 更改了它的工作目录os.chdir(),它在Example_directory.

os.chdir()before不需要使用os.mkdir(),直接创建为子目录即可。

os.mkdir("Example_directory/New_folder_name")

推荐阅读