Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。
os.rename()
Python中的方法用於重命名文件或目錄。
此方法將源文件/目錄重命名為指定的目標文件/目錄。
用法: os.rename(source, destination, *, src_dir_fd = None, dst_dir_fd = None)
參數:
source:代表文件係統路徑的path-like對象。這是要重命名的源文件路徑。
destination:代表文件係統路徑的path-like對象。
src_dir_fd(可選):引用目錄的文件描述符。
dst_dir_fd(可選):引用目錄的文件描述符。
返回類型:此方法不返回任何值。
代碼1:用於
os.rename()
方法# Python program to explain os.rename() method
# importing os module
import os
# Source file path
source = 'GeeksforGeeks/file.txt'
# destination file path
dest = 'GeekforGeeks/newfile.txt'
# Now rename the source path
# to destination path
# using os.rename() method
os.rename(source, dest)
print("Source path renamed to destination path successfully.")
輸出:
Source path renamed to destination path successfully.
代碼2:處理可能的錯誤
# Python program to explain os.rename() method
# importing os module
import os
# Source file path
source = './GeeksforGeeks/file.txt'
# destination file path
dest = './GeeksforGeeks/dir'
# try renaming the source path
# to destination path
# using os.rename() method
try :
os.rename(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:
print(error)
輸出:
Source is a file but destination is a directory.
參考: https://docs.python.org/3/library/os.html#os.rename
相關用法
- Python os.dup()用法及代碼示例
- Python next()用法及代碼示例
- Python set()用法及代碼示例
- Python object()用法及代碼示例
- Python bytes()用法及代碼示例
- Python os.times()用法及代碼示例
- Python os.chmod用法及代碼示例
- Python hash()用法及代碼示例
- Python os.ftruncate()用法及代碼示例
- Python os.truncate()用法及代碼示例
- Python os.fsdecode()用法及代碼示例
- Python dict pop()用法及代碼示例
- Python os.abort()用法及代碼示例
- Python os.WEXITSTATUS()用法及代碼示例
注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.rename() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。