python實(shí)現(xiàn)文件拷貝到其他目錄
在Python中,可以使用標(biāo)準(zhǔn)庫中的shutil模塊實(shí)現(xiàn)文件拷貝。以下是一個(gè)完整的代碼示例:
import shutil
import os
# 源文件路徑
src_file = "source_folder/example.py"
# 目標(biāo)目錄路徑
dst_dir = "target_folder"
# 檢查目標(biāo)目錄是否存在,不存在則創(chuàng)建
os.makedirs(dst_dir, exist_ok=True)
# 構(gòu)造目標(biāo)文件路徑
dst_file = os.path.join(dst_dir, os.path.basename(src_file))
try:
# 執(zhí)行拷貝操作(保留元數(shù)據(jù))
shutil.copy2(src_file, dst_file)
print(f"文件已成功拷貝到:{dst_file}")
except FileNotFoundError:
print(f"錯(cuò)誤:源文件 {src_file} 不存在")
except PermissionError:
print("錯(cuò)誤:權(quán)限不足,無法寫入目標(biāo)目錄")
except Exception as e:
print(f"拷貝過程中發(fā)生錯(cuò)誤:{str(e)}")
關(guān)鍵點(diǎn)說明:
- 路徑處理:使用
os.path.join和os.path.basename確保路徑跨平臺(tái)兼容 - 目錄創(chuàng)建:
os.makedirs的exist_ok=True參數(shù)會(huì)自動(dòng)創(chuàng)建目標(biāo)目錄 - 保留元數(shù)據(jù):
shutil.copy2會(huì)保留原始文件的創(chuàng)建/修改時(shí)間 - 錯(cuò)誤處理:捕獲常見異常(文件不存在、權(quán)限問題等)
擴(kuò)展功能:
1.如果要批量拷貝目錄下的所有.py文件:
import glob
source_dir = "source_folder"
target_dir = "target_folder"
os.makedirs(target_dir, exist_ok=True)
for py_file in glob.glob(os.path.join(source_dir, "*.py")):
shutil.copy2(py_file, os.path.join(target_dir, os.path.basename(py_file)))
2.拷貝多個(gè)文件到新目錄
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import shutil
import os
import logging
logging.basicConfig(level=logging.INFO)
base_disk_path = "D:\\"
source_paths = [
"/files/psPayOffRequest/31bab034-6646-4ade-bc7c-e49bb2d6e6a2.jpg",
"/files/psPayOffRequest/0857c67a-8f48-452c-8cfe-c2461c5bd498.jpg",
"/files/psPayOffRequest/3d36e2c1-8ae1-49f1-971f-468999541975.jpg"
]
target_directory = "d:/new_directory/"
if not os.path.exists(target_directory):
os.makedirs(target_directory)
for source_path in source_paths:
full_source_path = os.path.join(base_disk_path, source_path.lstrip("/"))
file_name = os.path.basename(full_source_path)
target_path = os.path.join(target_directory, file_name)
logging.info(f"Copying {full_source_path} to {target_path}")
shutil.copy(full_source_path, target_path)
3.拷貝指定文件夾或文件到指定目錄
import os
import shutil
primary_dir = r'原始文件夾'
target_dir = r'目標(biāo)文件夾'
def str_change(str):
if not 'bin' in str:
return str
else:
aa, bb = str.split('bin')
return aa + bb
def func_copy(primary_dir, target_dir): # 拷貝方法 把原始文件夾的所有文件夾和文件 按照同樣的名字拷貝到目標(biāo)文件夾中
# 遍歷filepath下所有文件,包括目錄
files = os.listdir(primary_dir)
for i in files: # i 是目錄下的文件或文件夾
i = os.path.join(primary_dir, i) # 字符串拼接
i_new = os.path.join(target_dir, i) # 目標(biāo)文件夾也要改變
if os.path.isdir(i): # 如果是文件夾
if not os.path.exists(i_new): # 如果沒新建過 新建同名目標(biāo)文件夾
os.makedirs(i_new)
func_copy(i, i_new) # 遞歸循環(huán)下一個(gè)目錄 復(fù)制目錄里面的內(nèi)容
else: # 不是文件夾 文件 判斷字符串是否有_bin 粘貼到指定位置 并且修改名字
oldname = i
newname = str_change(i_new)
print(oldname)
print(newname)
if not os.path.exists(newname): # 如果文件不存在,存在了就不拷貝了
shutil.copyfile(oldname, newname)
if __name__ == '__main__':
func_copy(primary_dir, target_dir)注意事項(xiàng):
- 拷貝大文件時(shí)建議使用
shutil.copy2而非shutil.copy,前者會(huì)保留更完整的元數(shù)據(jù) - 跨文件系統(tǒng)拷貝時(shí),
shutil.copy2可能需要更長時(shí)間 - 目標(biāo)目錄需要寫入權(quán)限
- 復(fù)制符號(hào)鏈接時(shí),默認(rèn)會(huì)復(fù)制鏈接指向的實(shí)際文件內(nèi)容
這個(gè)方法在Windows/Linux/macOS均可使用,無需額外安裝依賴庫。
到此這篇關(guān)于python實(shí)現(xiàn)文件拷貝到其他目錄的文章就介紹到這了,更多相關(guān)python文件拷貝內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python實(shí)現(xiàn)ftp文件傳輸系統(tǒng)(案例分析)
最近做了一個(gè)簡單的文件傳輸系統(tǒng),基于ftp協(xié)議,使用python語言開發(fā),雖然python里面已經(jīng)有ftplib模塊,可以很容易的實(shí)現(xiàn)ftp服務(wù)器,這篇文章主要介紹了python實(shí)現(xiàn)ftp文件傳輸系統(tǒng)的案例分析,需要的朋友可以參考下2020-03-03
基于Python實(shí)現(xiàn)二維圖像雙線性插值
雙線性插值,又稱為雙線性內(nèi)插。在數(shù)學(xué)上,雙線性插值是有兩個(gè)變量的插值函數(shù)的線性插值擴(kuò)展,其核心思想是在兩個(gè)方向分別進(jìn)行一次線性插值。本文將用Python實(shí)現(xiàn)二維圖像雙線性插值,感興趣的可以了解下2022-06-06
python中關(guān)于os.path.pardir的一些坑
這篇文章主要介紹了python中關(guān)于os.path.pardir的一些坑及解決方案,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-09-09
python django 訪問靜態(tài)文件出現(xiàn)404或500錯(cuò)誤
這篇文章主要介紹了python django 訪問靜態(tài)文件出現(xiàn)404或500錯(cuò)誤的相關(guān)資料,需要的朋友可以參考下2017-01-01
基于Python實(shí)現(xiàn)一個(gè)圖片壓縮工具
圖片壓縮是在保持圖像質(zhì)量的同時(shí)減小圖像文件大小的過程,本文將學(xué)習(xí)如何使用Python來實(shí)現(xiàn)一個(gè)簡單但功能強(qiáng)大的圖片壓縮工具,以及如何在不同情境下進(jìn)行圖片壓縮,希望對大家有所幫助2024-01-01
Python新手們?nèi)菀追傅膸讉€(gè)錯(cuò)誤總結(jié)
python語言里面有一些小的坑,特別容易弄混弄錯(cuò),初學(xué)者若不注意的話,很容易坑進(jìn)去,下面我給大家深入解析一些這幾個(gè)坑,希望對初學(xué)者有所幫助,需要的朋友可以參考學(xué)習(xí),下面來一起看看吧。2017-04-04

