利用Python把文件移動到另一個文件夾的方法
在Python中,文件移動可通過shutil.move()函數(shù)實現(xiàn)。以下是完整操作指南:
基礎(chǔ)移動(單個文件)
import shutil import os # 定義源文件和目標路徑 source_file = '/path/source.txt' target_folder = '/path/target_folder/' # 確保目標目錄存在 os.makedirs(target_folder, exist_ok=True) # 執(zhí)行移動 shutil.move(source_file, target_folder)
批量移動(帶文件類型過濾)
import os
import shutil
import glob
source_dir = '/path/source_folder'
target_dir = '/path/target_folder'
os.makedirs(target_dir, exist_ok=True)
# 移動所有.ts文件
for ts_file in glob.glob(os.path.join(source_dir, '*.ts')):
shutil.move(ts_file, target_dir)
關(guān)鍵特性說明
- 自動覆蓋:目標目錄存在同名文件時自動覆蓋
- 目錄創(chuàng)建:
os.makedirs(..., exist_ok=True)自動創(chuàng)建目標目錄 - 跨設(shè)備支持:支持不同磁盤分區(qū)間的文件移動
- 錯誤處理:建議添加try-except捕獲
FileNotFoundError等異常
高級技巧
保留目錄結(jié)構(gòu)移動
import os
import shutil
source = '/data/source'
target = '/data/target'
for root, dirs, files in os.walk(source):
for file in files:
src_path = os.path.join(root, file)
rel_path = os.path.relpath(src_path, source)
target_path = os.path.join(target, rel_path)
os.makedirs(os.path.dirname(target_path), exist_ok=True)
shutil.move(src_path, target_path)
移動并重命名
shutil.move('/source/file.txt', '/target/renamed_file.txt')
注意事項
- 移動系統(tǒng)文件時需管理員權(quán)限
- 移動過程中文件被占用會導(dǎo)致操作失敗
- 跨文件系統(tǒng)移動實質(zhì)是復(fù)制+刪除
- 建議先測試
shutil.copy2()保留元數(shù)據(jù)
到此這篇關(guān)于利用Python把文件移動到另一個文件夾的方法的文章就介紹到這了,更多相關(guān)Python文件移動到另一個文件夾內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Python虛擬環(huán)境管理工具Conda的使用指南
在Python開發(fā)中,虛擬環(huán)境是管理項目依賴的核心工具,常見的虛擬環(huán)境管理工具包括venv、virtualenv和Conda,本文將詳細介紹這三種工具的使用方式并對比其特點與適用場景2025-06-06
Python輸出漢字字庫及將文字轉(zhuǎn)換為圖片的方法
這篇文章主要介紹了Python輸出漢字字庫及將文字轉(zhuǎn)換為圖片的方法,分別用到了codecs模塊和pygame模塊,需要的朋友可以參考下2016-06-06
Python如何用str.format()批量生成網(wǎng)址(豆瓣讀書為例)
這篇文章主要介紹了Python如何用str.format()批量生成網(wǎng)址(豆瓣讀書為例),文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-09-09
macOS M1(Apple Silicon)安裝配置Conda環(huán)境的具體實現(xiàn)
由于常用的Anaconda和Miniconda現(xiàn)在都沒有提供M1處理器支持的conda環(huán)境,以下是conda-forge提供的miniforge,感興趣的可以了解一下2021-08-08
python爬蟲實戰(zhàn)之最簡單的網(wǎng)頁爬蟲教程
在我們?nèi)粘I暇W(wǎng)瀏覽網(wǎng)頁的時候,經(jīng)常會看到一些好看的圖片,我們就希望把這些圖片保存下載,或者用戶用來做桌面壁紙,或者用來做設(shè)計的素材。下面這篇文章就來給大家介紹了關(guān)于利用python實現(xiàn)最簡單的網(wǎng)頁爬蟲的相關(guān)資料,需要的朋友可以參考借鑒,下面來一起看看吧。2017-08-08

