📜  Python – os.replace() 方法

📅  最后修改于: 2022-05-13 01:55:22.391000             🧑  作者: Mango

Python – os.replace() 方法

先决条件: Python中的 OS 模块。

Python中的os.replace()方法用于重命名文件或目录。如果目标是一个目录,将引发OSError 。如果目标存在并且是一个文件,如果执行的操作用户有权限,它将被无误地替换。如果源和目标位于不同的文件系统上,则此方法可能会失败。

代码 #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.