Python 內建了複製檔案及移動檔案的功能.
Python 複製檔案:
在 Python 複製檔案可以用 shutil.copy(), 語法是:
shutil.copy(src,dst)
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import os import shutil # Source file source = "/var/www/html/file.txt" # Destination file destination = "/var/www/html/file.txt.bak" # Copy source to destination dest = shutil.copyfile(source, destination) # Print path of new file print("Destination path: ", dest) |
Python 移動檔案
在 Python 用 os.rename() 移動檔案, 語法跟 shutil.copy() 差不多:
os.rename(src, dst)
例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import os # Source file source = "/var/www/html/file.txt" # Destination file destination = "/var/www/html/file.txt.bak" # Move source to destination or.rename(source, destination) # Print path of new file print("File moved to: ", dest) |