Shutil模塊Python提供了許多對文件和文件集合進行高級操作的函數。它屬於Python的標準實用程序模塊。該模塊有助於自動執行文件和目錄的複製和刪除過程。
shutil.move()
方法將文件或目錄(源)遞歸移動到另一個位置(目標)並返回目標。如果目標目錄已經存在,則將src移動到該目錄中。如果目標已經存在但不是目錄,則可能會被覆蓋,具體取決於os.rename()
語義。
用法: shutil.move(source, destination, copy_function = copy2)
參數:
source: 代表源文件路徑的字符串。
destination: 代表目標目錄路徑的字符串。
copy_function(可選):此參數的默認值為copy2。我們可以為該參數使用其他複製函數,例如複製,複製樹等。
返回值:此方法返回一個表示新創建文件路徑的字符串。
範例1:
使用shutil.move()
將文件從源移動到目標的方法
# Python program to explain shutil.move() method
# importing os module
import os
# importing shutil module
import shutil
# path
path = 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
# List files and directories
# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
print("Before moving file:")
print(os.listdir(path))
# Source path
source = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/source'
# Destination path
destination = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/destination'
# Move the content of
# source to destination
dest = shutil.move(source, destination)
# List files and directories
# in "C:/Users / Rajnish / Desktop / GeeksforGeeks"
print("After moving file:")
print(os.listdir(path))
# Print path of newly
# created file
print("Destination path:", dest)
輸出:
Before moving file: ['source'] After moving file: ['destination'] Destination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination
範例2:
使用shutil.move()
使用移動文件的方法shutil.copytree()
方法和目標目錄已存在。
# Python program to explain shutil.move() method
# importing os module
import os
# importing shutil module
import shutil
# path
path = 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
# List files and directories
# in 'C:/Users/Rajnish/Desktop/GeeksforGeeks'
print("Before moving file:")
print(os.listdir(path))
# Source path
source = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/source'
# Destination path
destination = 'C:/Users/Rajnish/Desktop/GeeksforGeeks/destination'
# Move the content of
# source to destination
# using shutil.copytree() as parameter
dest = shutil.move(source, destination, copy_function = shutil.copytree)
# List files and directories
# in "C:/Users / Rajnish / Desktop / GeeksforGeeks"
print("After moving file:")
print(os.listdir(path))
# Print path of newly
# created file
print("Destination path:", dest)
輸出:
Before moving file: ['destination', 'source'] After moving file: ['destination'] Destination path: C:/Users/Rajnish/Desktop/GeeksforGeeks/destination\source
相關用法
- Python next()用法及代碼示例
- Python os.dup()用法及代碼示例
- Python set()用法及代碼示例
- Python os.abort()用法及代碼示例
- Python os.WEXITSTATUS()用法及代碼示例
- Python os.fchmod()用法及代碼示例
- Python PIL getpixel()用法及代碼示例
- Python PIL putpixel()用法及代碼示例
- Python os.sysconf()用法及代碼示例
- Python os.confstr()用法及代碼示例
- Python os._exit()用法及代碼示例
- Python cmath.log()用法及代碼示例
- Python Tensorflow cos()用法及代碼示例
- Python sympy.rf()用法及代碼示例
注:本文由純淨天空篩選整理自Rajnis09大神的英文原創作品 Python | shutil.move() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。