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可能需要更長(zhǎng)時(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)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python通過30秒就能學(xué)會(huì)的漂亮短程序代碼(過程全解)
這篇文章主要介紹了Python之30秒就能學(xué)會(huì)的漂亮短程序代碼,本文通過實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-10-10
django數(shù)據(jù)庫報(bào)錯(cuò)解決匯總:django.db.utils.OperationalError?1045,1049,
這篇文章主要給大家介紹了關(guān)于django數(shù)據(jù)庫報(bào)錯(cuò)解決:django.db.utils.OperationalError?1045,1049,2003的相關(guān)資料,文中將解決的辦法介紹的非常詳細(xì),需要的朋友可以參考下2023-02-02
python requests更換代理適用于IP頻率限制的方法
今天小編就為大家分享一篇python requests更換代理適用于IP頻率限制的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-08-08
Python Web項(xiàng)目Cherrypy使用方法鏡像
這篇文章主要介紹了Python Web項(xiàng)目Cherrypy使用方法鏡像,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-11-11
使用qt quick-ListView仿微信好友列表和聊天列表的示例代碼
本文以微信好友列表為例給大家學(xué)習(xí)listview的相關(guān)知識(shí),通過實(shí)例demo給大家詳解qt quick-ListView仿微信好友列表和聊天列表的實(shí)現(xiàn)方法,需要的朋友參考下吧2021-06-06

