检查给定路径中是否存在文件夹,如果不存在,则创建一个文件夹

2024-06-26 00:22:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我想检查路径中是否存在名为“Output folder”的文件夹

D:\LaptopData\ISIS project\test\d0_63_b4_01_18_ba\00_17_41_41_00_0e

如果名为“Output folder”的文件夹不存在,则在那里创建该文件夹。你知道吗

有谁能帮我提供一个解决方案吗?你知道吗


Tags: test路径project文件夹outputfolder解决方案isis
3条回答

最好的方法是使用os.mkdirs,比如

os.makedirs(name, mode=0o777, exist_ok=False)

Recursive directory creation function. Like mkdir(), but makes a intermediate-level directories needed to contain the leaf directory.

The mode parameter is passed to mkdir() for creating the leaf directory; see the mkdir() description for how it is interpreted. To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs(). The file permission bits of existing parent directories are not changed.

>>> os.mkdirs(path, exist_ok=True) 
# which will not raise an error if the `path` already exists
# and it will recursive create the paths, if the preceding path doesn't exist

或者如果你在python3,使用pathliblike

Path.mkdir(mode=0o777, parents=False, exist_ok=False)

Create a new directory at this given path. If mode is given, it is combined with the process’ umask value to determine the file mode and access flags. If the path already exists, FileExistsError is raised.

If parents is true, any missing parents of this path are created as needed; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).

If parents is false (the default), a missing parent raises FileNotFoundError. > If exist_ok is false (the default), FileExistsError is raised if the target directory already exists.

If exist_ok is true, FileExistsError exceptions will be ignored (same behavior as the POSIX mkdir -p command), but only if the last path component is not an existing non-directory file.

Changed in version 3.5: The exist_ok parameter was added.

>>> path = pathlib.Path(somepath)
>>> path.mkdir(parents=True, exist_ok=True)
import os
import os.path

folder = "abc"
os.chdir(".")
print("current dir is: %s" % (os.getcwd()))

if os.path.isdir(folder):
    print("Exists")
else:
    print("Doesn't exists")
    os.mkdir(folder)

我希望这有帮助

  • 搜索文件夹是否存在,它将返回truefalse
    os.path.exists('<folder-path>')
  • 创建新文件夹:os.mkdir('<folder-path>')

注意:导入模块需要import os。你知道吗

希望您能根据自己的要求用以上两个函数来编写逻辑。你知道吗

相关问题 更多 >