在WSL上调用`os.mkdir`时出现“没有这样的文件或目录”错误。

huangapple go评论97阅读模式
英文:

" No such file or directory" error when calling `os.mkdir` on WSL

问题

我的笔记本电脑的主要系统是Windows,但也安装了Windows子系统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

对于嵌套目录(在任何操作系统上),可以使用Python.Docs:os.makedirs(name, mode=0o777, exist_ok=False)函数,该函数说明如下(强调部分为我添加):

递归创建目录的函数。类似于mkdir(),但会创建所有需要包含叶子目录的中间级目录。

当然,也可以使用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.

huangapple
  • 本文由 发表于 2023年8月9日 15:37:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/76865565.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定