python - 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 中创建文件夹的另一种方法吗?
解决方案
File_directory
大概存在于进程的原始工作目录中。但是你用 更改了它的工作目录os.chdir()
,它在Example_directory
.
os.chdir()
before不需要使用os.mkdir()
,直接创建为子目录即可。
os.mkdir("Example_directory/New_folder_name")
推荐阅读
- c++ - 如何使用标准工具计算给定大小和内容检查的 const char* 哈希
- python - 如何为深度学习中的多类创建多维 NumPy 数组?
- elasticsearch - Elasticsearch 索引无法识别日期(Logstash 管道)
- hive - 我尝试的 Hive 插入是否有解决方法
- jenkins - 以编程方式查找 Job DSL 插件生成的作业
- android - 在没有隐式广播的情况下收听 Oreo+ android 设备中的来电/去电
- regex - 该语言的哪个正则表达式是“最干净”或最有效的?
- python - 将图像文件上传到数据库
- javascript - 如何在javascript中的关联数组上使用数组索引生成数组键
- javascript - 添加文档并将子集合添加到该文档 Firestore