在Python中创建目录
Python中的 OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os
和os.path
模块包含许多与文件系统交互的函数。 os 模块中的所有函数在文件名和路径无效或不可访问的情况下,或具有正确类型但操作系统不接受的其他参数的情况下引发OSError
。
在 OS 模块中有不同的方法可用于创建导向器。这些都是 -
- os.mkdir()
- os.makedirs()
使用 os.mkdir()
Python中的os.mkdir()
方法用于以指定的数字模式创建名为 path 的目录。如果要创建的目录已经存在,则此方法引发FileExistsError
。
Syntax: os.mkdir(path, mode = 0o777, *, dir_fd = None)
Parameter:
path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
mode (optional): A Integer value representing mode of the directory to be created. If this parameter is omitted then default value Oo777 is used.
dir_fd (optional): A file descriptor referring to a directory. The default value of this parameter is None.
If the specified path is absolute then dir_fd is ignored.
Note: The ‘*’ in parameter list indicates that all following parameters (Here in our case ‘dir_fd’) are keyword-only parameters and they can be provided using their name, not as positional parameter.
Return Type: This method does not return any value.
示例 #1:使用os.mkdir()
方法创建目录/文件
# Python program to explain os.mkdir() method
# importing os module
import os
# Directory
directory = "GeeksforGeeks"
# Parent Directory path
parent_dir = "D:/Pycharm projects/"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'GeeksForGeeks' in
# '/home / User / Documents'
os.mkdir(path)
print("Directory '% s' created" % directory)
# Directory
directory = "Geeks"
# Parent Directory path
parent_dir = "D:/Pycharm projects"
# mode
mode = 0o666
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'GeeksForGeeks' in
# '/home / User / Documents'
# with mode 0o666
os.mkdir(path, mode)
print("Directory '% s' created" % directory)
输出:
Directory 'GeeksforGeeks' created
Directory 'Geeks' created
示例 #2:使用os.mkdir()
方法时出错。
# Python program to explain os.mkdir() method
# importing os module
import os
# Directory
directory = "GeeksForGeeks"
# Parent Directory path
parent_dir = "D:/Pycharm projects/"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'GeeksForGeeks' in
# '/home / User / Documents'
os.mkdir(path)
print("Directory '% s' created" % directory)
# if directory / file that
# is to be created already
# exists then 'FileExistsError'
# will be raised by os.mkdir() method
# Similarly, if the specified path
# is invalid 'FileNotFoundError' Error
# will be raised
输出:
Traceback (most recent call last):
File "gfg.py", line 18, in
os.mkdir(path)
FileExistsError: [WinError 183] Cannot create a file when that file /
/already exists: 'D:/Pycharm projects/GeeksForGeeks'
示例 #3:使用os.mkdir()
方法时处理错误。
# Python program to explain os.mkdir() method
# importing os module
import os
# path
path = 'D:/Pycharm projects / GeeksForGeeks'
# Create the directory
# 'GeeksForGeeks' in
# '/home / User / Documents'
try:
os.mkdir(path)
except OSError as error:
print(error)
输出:
[WinError 183] Cannot create a file when that file/
/already exists: 'D:/Pycharm projects/GeeksForGeeks'
使用 os.makedirs()
Python中的os.makedirs()
方法用于递归创建目录。这意味着如果缺少任何中间级目录,则在创建叶目录时, os.makedirs()
方法将全部创建它们。
例如,考虑以下路径:
D:/Pycharm projects/GeeksForGeeks/Authors/Nikhil
假设我们要创建目录“Nikhil”,但目录“GeeksForGeeks”和“Authors”在路径中不可用。然后os.makedirs()
方法将在指定路径中创建所有不可用/丢失的目录。将首先创建“GeeksForGeeks”和“Authors”,然后创建“Nikhil”目录。
Syntax: os.makedirs(path, mode = 0o777, exist_ok = False)
Parameter:
path: A path-like object representing a file system path. A path-like object is either a string or bytes object representing a path.
mode (optional): A Integer value representing mode of the newly created directory. If this parameter is omitted then the default value Oo777 is used.
exist_ok (optional): A default value False is used for this parameter. If the target directory already exists an OSError is raised if its value is False otherwise not.
Return Type: This method does not return any value.
示例 #1:使用os.makedirs()
方法创建目录。
# Python program to explain os.makedirs() method
# importing os module
import os
# Leaf directory
directory = "Nikhil"
# Parent Directories
parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'Nikhil'
os.makedirs(path)
print("Directory '% s' created" % directory)
# Directory 'GeeksForGeeks' and 'Authors' will
# be created too
# if it does not exists
# Leaf directory
directory = "c"
# Parent Directories
parent_dir = "D:/Pycharm projects/GeeksforGeeks/a/b"
# mode
mode = 0o666
path = os.path.join(parent_dir, directory)
# Create the directory 'c'
os.makedirs(path, mode)
print("Directory '% s' created" % directory)
# 'GeeksForGeeks', 'a', and 'b'
# will also be created if
# it does not exists
# If any of the intermediate level
# directory is missing
# os.makedirs() method will
# create them
# os.makedirs() method can be
# used to create a directory tree
输出:
Directory 'Nikhil' created
Directory 'c' created
示例 #2:
# Python program to explain os.makedirs() method
# importing os module
import os
# os.makedirs() method will raise
# an OSError if the directory
# to be created already exists
# Directory
directory = "Nikhil"
# Parent Directory path
parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'Nikhil'
os.makedirs(path)
print("Directory '% s' created" % directory)
输出:
Traceback (most recent call last):
File "gfg.py", line 22, in
os.makedirs(path)
File "C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python/
/ \Python38-32\lib\os.py", line 221, in makedirs
mkdir(name, mode)
FileExistsError: [WinError 183] Cannot create a file when that/
/ file already exists: 'D:/Pycharm projects/GeeksForGeeks/Authors\\Nikhil'
示例 #3:在使用 os.makedirs() 方法时处理错误。
# Python program to explain os.makedirs() method
# importing os module
import os
# os.makedirs() method will raise
# an OSError if the directory
# to be created already exists
# But It can be suppressed by
# setting the value of a parameter
# exist_ok as True
# Directory
directory = "Nikhil"
# Parent Directory path
parent_dir = "D:/Pycharm projects/GeeksForGeeks/Authors"
# Path
path = os.path.join(parent_dir, directory)
# Create the directory
# 'Nikhil'
try:
os.makedirs(path, exist_ok = True)
print("Directory '%s' created successfully" % directory)
except OSError as error:
print("Directory '%s' can not be created" % directory)
# By setting exist_ok as True
# error caused due already
# existing directory can be suppressed
# but other OSError may be raised
# due to other error like
# invalid path name
输出:
Directory 'Nikhil' created successfully