英文:
" No such file or directory" error when calling `os.mkdir` on WSL
问题
我的笔记本电脑的主要系统是Windows,但也安装了Windows Subsystem for Linux(WSL)。当我开始在WSL上安装的Python中编写代码(在VSCode的“连接到WSL”选项中),发现os.mkdir
不如预期那样工作:
import os
print(os.uname()[0]) # 'Linux'
path = os.path.join("New", "2023") # path = "New/2023"
os.mkdir(path)
引发FileNotFoundError: [Errno 2] No such file or directory: 'New/2023'
错误。
我该如何修复它?为了提供更多背景信息:这是项目的一部分,我需要自动创建一些新目录并将生成的文件保存到其中,它必须是跨操作系统的,因为一些用户使用Windows,一些用户使用Linux。
英文:
My laptop's main system is Windows, but it has also Windows Subsystem for Linux (WSL) installed. When I started to write code in python installed on WSL (Connect to WSL option in VSCode), it turned out that os.mkdir
doesn't work as expected:
import os
print(os.uname()[0]) # 'Linux'
path = os.path.join("New", "2023") # path = "New/2023"
os.mkdir(path)
raises FileNotFoundError: [Errno 2] No such file or directory: 'New/2023'
.
How can I fix it? For more context: this is part of project when I need to automate creation of some new directories and save generated files to them and it must be OS independent because some users use Windows and some Linux.
答案1
得分: 2
对于嵌套目录(在任何OS上),请使用 [Python.Docs]: os.makedirs(name, mode=0o777, exist_ok=False) 中描述的 递归目录创建 函数。与 mkdir() 类似,但会创建所有必需的中间级目录以包含叶目录。
当然,也可以使用 mkdir 来实现相同的目标,但对于路径中不存在的每个目录(从外到内),需要调用一次,这几乎就是 makedirs 所做的事情。
英文:
For nested directories (on any OS), use [Python.Docs]: os.makedirs(name, mode=0o777, exist_ok=False) which states (emphasis is mine):
> Recursive directory creation function. Like mkdir(), but makes all intermediate-level directories needed to contain the leaf directory.
Of course, the goal could be also achieved using mkdir, but there should be one call for each directory (from outer to inner) in the path that doesn't exist, which is pretty much what makedirs does.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论