简体   繁体   English

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

[英]check if a folder exists in a given path and if not then create a folder there

I want to check if a folder by the name "Output Folder" exists at the path我想检查路径中是否存在名为“输出文件夹”的文件夹

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

if the folder by the name "Output Folder" does not exist then create that folder there.如果名称为“输出文件夹”的文件夹不存在,则在此处创建该文件夹。

can anyone please help with providing a solution for this?任何人都可以帮忙提供解决方案吗?

The best way would be to use os.makedirs like,最好的方法是使用os.makedirs 之类的,

os.makedirs(name, mode=0o777, exist_ok=False) os.makedirs(名称,模式=0o777,exist_ok=False)

Recursive directory creation function.递归目录创建功能。 Like mkdir(), but makes a intermediate-level directories needed to contain the leaf directory.与 mkdir() 类似,但创建了一个包含叶目录所需的中间级目录。

The mode parameter is passed to mkdir() for creating the leaf directory; mode 参数传递给 mkdir() 用于创建叶子目录; see the mkdir() description for how it is interpreted.请参阅 mkdir() 描述以了解它是如何解释的。 To set the file permission bits of any newly-created parent directories you can set the umask before invoking makedirs().要设置任何新创建的父目录的文件权限位,您可以在调用 makedirs() 之前设置 umask。 The file permission bits of existing parent directories are not changed.现有父目录的文件权限位不会更改。

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

or if you are on python3 , using pathlib like,或者如果你在python3上,使用pathlib 之类的,

Path.mkdir(mode=0o777, parents=False, exist_ok=False) Path.mkdir(模式=0o777,父母=假,exist_ok=假)

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.如果给出了模式,则将其与进程的 umask 值组合以确定文件模式和访问标志。 If the path already exists, FileExistsError is raised.如果路径已存在,则引发 FileExistsError。

If parents is true, any missing parents of this path are created as needed;如果 parents 为真,则根据需要创建此路径的任何缺少的 parent; they are created with the default permissions without taking mode into account (mimicking the POSIX mkdir -p command).它们是使用默认权限创建的,不考虑模式(模仿 POSIX mkdir -p 命令)。

If parents is false (the default), a missing parent raises FileNotFoundError .如果 parents 为 false(默认值),则缺少的 parent 会引发FileNotFoundError > If exist_ok is false (the default), FileExistsError is raised if the target directory already exists. > 如果 exists_ok 为 false(默认值),如果目标目录已经存在,则会引发FileExistsError

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.如果exist_ok为真, FileExistsError异常将被忽略(与 POSIX mkdir -p command相同),但前提是最后一个路径组件不是现有的非目录文件。

Changed in version 3.5: The exist_ok parameter was added.在 3.5 版更改: 添加了 exists_ok 参数。

>>> import pathlib
>>> 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)

I hope this helps我希望这有帮助

pathlib application where csv files need to be created inside a csv folder under parent directory, from a xlsx file with full path (eg, taken with Path Copy Copy ) provided. pathlib 应用程序,其中 csv 文件需要在父目录下的 csv 文件夹中创建,来自提供的完整路径(例如,使用Path Copy Copy获取)的 xlsx 文件。
If exist_ok is true, FileExistsError exceptions will be ignored, if directory is already created.如果exist_ok 为真,则FileExistsError 异常将被忽略,如果已经创建了目录。

from pathlib import Path

wrkfl = 'C:/xlsx/my.xlsx'  # path get from Path Copy Copy context menu
xls_file = Path(wrkfl)
(xls_file.parent / 'csv').mkdir(parents=True, exist_ok=True) 
  • Search for folder whether it exists or not, it will return true or false :搜索文件夹是否存在,它会返回truefalse
    os.path.exists('<folder-path>')
  • Create a new folder: os.mkdir('<folder-path>')创建一个新文件夹: os.mkdir('<folder-path>')

Note: import os will be required to import the module.注意: import os将需要导入模块。

Hope you can write the logic using above two functions as per your requirement.希望您可以根据您的要求使用上述两个函数编写逻辑。

Getting help from the answers above, I reached this solution从上面的答案中获得帮助,我达到了这个解决方案

if not os.path.exists(os.getcwd() + '/' + folderName):
    os.makedirs(os.getcwd() + '/' + folderName, exist_ok=True) 
import os


def folder_creat(name, directory):
    os.chdir(directory)
    fileli = os.listdir()
    if name in fileli:
        print(f'Folder "{name}" exist!')
    else:
        os.mkdir(name)
        print(f'Folder "{name}" succesfully created!')
        return


folder_creat('Output Folder', r'D:\LaptopData\ISIS project\test\d0_63_b4_01_18_ba\00_17_41_41_00_0e')

This piece of code does the exactly what you wanted.这段代码正是你想要的。 First gets the absolute path, then joins folder wanted in the path, and finally creates it if it is not exists.首先获取绝对路径,然后加入路径中想要的文件夹,如果它不存在,最后创建它。

import os

# Gets current working directory
path = os.getcwd()

# Joins the folder that we wanted to create
folder_name = 'output'
path = os.path.join(path, folder_name) 

# Creates the folder, and checks if it is created or not.
os.makedirs(path, exist_ok=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM