Python copyfile 複製檔案用法與範例

本篇介紹 Python copyfile 複製檔案用法與範例。
以下範例是在 Python 3 環境下測試過。

在 Python 中要複製檔案可以使用 shutil.copyfile()
使用 shutil.copyfile 時,需先 import shutil

程式碼如下,

python-shutil-copyfile.py
1
2
3
4
5
6
7
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import shutil

src = 'old.txt'
dst = 'new.txt'
shutil.copyfile(src, dst)

也可以用 shutil.copyfile() 將檔案從某資料夾複製到另外一個新的資料夾,但是這個目的端的資料夾一定要存在否則會出現 IOError 錯誤,
可以先用 os.path.exists() 判斷資料夾是否存在,不存在的話用 os.mkdir() 建立這個資料夾即可,

python-shutil-copyfile2.py
1
2
3
4
5
6
7
8
9
10
11
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import shutil
import os

src = 'oldfolder/old.txt'
dst = 'newfolder/new.txt'

if not os.path.exists('newfolder'):
os.mkdir('newfolder')
shutil.copyfile(src, dst)

其它相關文章推薦
Python 判斷檢查檔案是否存在 os.path.isfile
Python 判斷資料夾是否存在 os.path.isdir
Python 判斷檢查路徑是否存在 exists
Python 去除空白與去除特殊字元 strip
Python 取出檔案名稱 basename
Python 取出目錄的路徑 dirname
Python 字串分割 split
Python 連接字串 join
Python 去除空白與去除特殊字元 strip