Python – os.replace() 方法
先决条件: Python中的 OS 模块。
Python中的os.replace()方法用于重命名文件或目录。如果目标是一个目录,将引发OSError 。如果目标存在并且是一个文件,如果执行的操作用户有权限,它将被无误地替换。如果源和目标位于不同的文件系统上,则此方法可能会失败。
Syntax: os.replace(source, destination, *, src_dir_fd=None, dst_dir_fd=None2)
Parameter:
- source: Name of file or directory which we want to rename.
- destination: Name which we want to give in destination.
- src_dir_id : This parameter stores the source directory’s or file,
file descripter referring to a directory. - dst_dir_fd: It is a file descriptor referring to a directory,
and the path to operate. It should be relative,
path will then be relative to that directory. If
the path is absolute, dir_fd is ignored.
Return Type: This method does not return any value.
代码 #1 :使用 os.replace() 方法重命名文件。
Python3
# Python program to explain os.replace() method
# importing os module
import os
# file name
file = "f.txt"
# File location which to rename
location = "d.txt"
# Path
path = os.replace(file, location)
# renamed the file f.txt to d.txt
print("File %s is renamed successfully" % file)
Python
# Python program to explain os.replace() method
# importing os module
import os
# Source file path
source = './file.txt'
# destination file path
dest = './da'
# try renaming the source path
# to destination path
# using os.rename() method
try:
os.replace(source, dest)
print("Source path renamed to destination path successfully.")
# If Source is a file
# but destination is a directory
except IsADirectoryError:
print("Source is a file but destination is a directory.")
# If source is a directory
# but destination is a file
except NotADirectoryError:
print("Source is a directory but destination is a file.")
# For permission related errors
except PermissionError:
print("Operation not permitted.")
# For other errors
except OSError as error:
输出:
File f.txt is renamed successfully
代码#2 :处理可能的错误。 (如果给予必要的权限,则输出将如下所示)
Python
# Python program to explain os.replace() method
# importing os module
import os
# Source file path
source = './file.txt'
# destination file path
dest = './da'
# try renaming the source path
# to destination path
# using os.rename() method
try:
os.replace(source, dest)
print("Source path renamed to destination path successfully.")
# If Source is a file
# but destination is a directory
except IsADirectoryError:
print("Source is a file but destination is a directory.")
# If source is a directory
# but destination is a file
except NotADirectoryError:
print("Source is a directory but destination is a file.")
# For permission related errors
except PermissionError:
print("Operation not permitted.")
# For other errors
except OSError as error:
输出:
Source is a file but destination is a directory.