0%

Copy file to different directory by python

前言

最近在移動資料,原本要去各個資料夾下複製再貼到新的資料夾,
但我想偷懶看能不能用python一次搬,結果還真的可以~
以下就簡單說明一下怎做的。

會用到的function

1
copyfile(src, dst)

說明:
簡單來說第一個參數是原檔案的舊路徑,第二個參數是把原檔案複製後的要放進去的新路徑。

實際操作

單一檔案

假設我要把某檔案example.txt複製一份後,
從舊路徑./old_dir/傳到新路徑./new_dir/

1
2
3
4
5
from shutil import copyfile

old_dir = './old_dir/'
new_dir = './new_dir/'
copyfile(old_dir + 'example.txt', new_dir + 'example.txt')

多個檔案

假設我要把舊路徑./old_dir/裡面所有的圖片檔.jpg
傳到新路徑./new_dir/

1
2
3
4
5
6
7
8
9
10
from shutil import copyfile
import os

old_dir = './old_dir/'
new_dir = './new_dir/'
files = os.listdir(old_dir)

for file in files:
if file.endswith('.jpg'):
copyfile(old_dir + file, new_dir + file)

以上,就是這麼簡單~