使用Python删除目录或文件
Python提供了不同的方法和函数来删除文件和目录。可以根据需要删除文件。 Python提供的各种方法是——
- 使用 os.remove()
- 使用 os.rmdir()
- 使用 shutil.rmtree()
使用 os.remove()
Python中的OS 模块提供了与操作系统交互的功能。 os 模块中的所有函数在文件名和路径无效或不可访问的情况下,或具有正确类型但操作系统不接受的其他参数的情况下引发OSError
。
Python中的os.remove()
方法用于删除或删除文件路径。此方法不能删除或删除目录。如果指定的路径是目录,则该方法将引发OSError
。
Syntax: os.remove(path, *, dir_fd = None)
Parameter:
path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.
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:假设文件夹中包含的文件为:
我们想从上面的文件夹中删除 file1。下面是实现。
# Python program to explain os.remove() method
# importing os module
import os
# File name
file = 'file1.txt'
# File location
location = "D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil/"
# Path
path = os.path.join(location, file)
# Remove the file
# 'file.txt'
os.remove(path)
输出:
示例2:如果指定的路径是目录。
# Python program to explain os.remove() method
# importing os module
import os
# Directory name
dir = "Nikhil"
# Path
location = "D:/Pycharm projects/GeeksforGeeks/Authors/"
path = os.path.join(location, dir)
# Remove the specified
# file path
os.remove(path)
print("% s has been removed successfully" % dir)
# if the specified path
# is a directory then
# 'IsADirectoryError' error
# will raised
# Similarly if the specified
# file path does not exists or
# is invalid then corresponding
# OSError will be raised
输出:
Traceback (most recent call last):
File "osremove.py", line 11, in
os.remove(path)
IsADirectoryError: [Errno 21] Is a directory: 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil'
示例 3:使用os.remove()
方法时处理错误。
# Python program to explain os.remove() method
# importing os module
import os
# path
path = 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil'
# Remove the specified
# file path
try:
os.remove(path)
print("% s removed successfully" % path)
except OSError as error:
print(error)
print("File path can not be removed")
输出:
[Errno 21] Is a directory: 'D:/Pycharm projects/GeeksforGeeks/Authors/Nikhil'
File path can not be removed
注意:要了解有关os.remove()
的更多信息,请单击此处。
使用 os.rmdir()
Python中的os.rmdir()
方法用于移除或删除一个空目录。如果指定的路径不是空目录,将引发OSError
。
Syntax: os.rmdir(path, *, dir_fd = None)
Parameter:
path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.
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:假设目录是 -
我们要删除目录 Geeks。下面是实现。
# Python program to explain os.rmdir() method
# importing os module
import os
# Directory name
directory = "Geeks"
# Parent Directory
parent = "D:/Pycharm projects/"
# Path
path = os.path.join(parent, directory)
# Remove the Directory
# "Geeks"
os.rmdir(path)
输出:
示例 2: using os.rmdir()
方法处理错误,
# Python program to explain os.rmdir() method
# importing os module
import os
# Directory name
directory = "GeeksforGeeks"
# Parent Directory
parent = "D:/Pycharm projects/"
# Path
path = os.path.join(parent, directory)
# Remove the Directory
# "GeeksforGeeks"
try:
os.rmdir(path)
print("Directory '% s' has been removed successfully" % directory)
except OSError as error:
print(error)
print("Directory '% s' can not be removed" % directory)
# if the specified path
# is not an empty directory
# then permission error will
# be raised
# similarly if specified path
# is invalid or is not a
# directory then corresponding
# OSError will be raised
输出:
[WinError 145] The directory is not empty: 'D:/Pycharm projects/GeeksforGeeks'
Directory 'GeeksforGeeks' can not be removed
注意:要了解有关os.rmdir()
的更多信息,请单击此处。
使用 shutil.rmtree()
shutil.rmtree() 用于删除整个目录树,路径必须指向目录(但不能指向目录的符号链接)。
Syntax: shutil.rmtree(path, ignore_errors=False, onerror=None)
Parameters:
path: A path-like object representing a file path. A path-like object is either a string or bytes object representing a path.
ignore_errors: If ignore_errors is true, errors resulting from failed removals will be ignored.
oneerror: If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror.
示例 1:假设目录和子目录如下。
# 父目录:
# 父目录内的目录:
# 子目录下的文件:
我们要删除目录作者。下面是实现。
# Python program to demonstrate
# shutil.rmtree()
import shutil
import os
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
# directory
dir = "Authors"
# path
path = os.path.join(location, dir)
# removing directory
shutil.rmtree(path)
输出:
示例 2:通过传递ignore_errors = True
。
# Python program to demonstrate
# shutil.rmtree()
import shutil
import os
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
# directory
dir = "Authors"
# path
path = os.path.join(location, dir)
# removing directory
shutil.rmtree(path, ignore_errors = False)
# making ignore_errors = True will not raise
# a FileNotFoundError
输出:
Traceback (most recent call last):
File “D:/Pycharm projects/gfg/gfg.py”, line 16, in
shutil.rmtree(path, ignore_errors=False)
File “C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.py”, line 730, in rmtree
return _rmtree_unsafe(path, onerror)
File “C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.py”, line 589, in _rmtree_unsafe
onerror(os.scandir, path, sys.exc_info())
File “C:\Users\Nikhil Aggarwal\AppData\Local\Programs\Python\Python38-32\lib\shutil.py”, line 586, in _rmtree_unsafe
with os.scandir(path) as scandir_it:
FileNotFoundError: [WinError 3] The system cannot find the path specified: ‘D:/Pycharm projects/GeeksforGeeks/Authors’
示例 3:通过传递 onerror
在onerror
中,应该传递一个必须包含三个参数的函数。
- 函数 –引发异常的函数。
- path –传递的路径名,在删除时引发异常
- excinfo – sys.exc_info() 引发的异常信息
下面是实现
# Python program to demonstrate
# shutil.rmtree()
import shutil
import os
# exception handler
def handler(func, path, exc_info):
print("Inside handler")
print(exc_info)
# location
location = "D:/Pycharm projects/GeeksforGeeks/"
# directory
dir = "Authors"
# path
path = os.path.join(location, dir)
# removing directory
shutil.rmtree(path, onerror = handler)
输出:
Inside handler
(
Inside handler
(
在评论中写代码?请使用 ide.geeksforgeeks.org,生成链接并在此处分享链接。