本文目录导读:

我来给你介绍几种Python文件移动的方法和案例。
基本文件移动方法
使用 shutil.move() - 最常用方法
import shutil
import os
# 移动单个文件
source_file = 'source.txt'
target_dir = 'target_folder/'
shutil.move(source_file, target_dir)
# 移动并重命名
shutil.move('old_name.txt', 'new_folder/new_name.txt')
使用 os.rename() - 简单移动
import os
# 在同一磁盘下移动
os.rename('source.txt', 'destination.txt')
# 跨目录移动(仅在同一个文件系统)
os.rename('folder1/file.txt', 'folder2/file.txt')
完整案例:批量文件迁移
import shutil
import os
from pathlib import Path
import glob
def move_files_with_pattern(source_dir, target_dir, pattern='*.*'):
"""
按文件模式批量移动文件
参数:
source_dir: 源目录
target_dir: 目标目录
pattern: 文件匹配模式,如 '*.txt', '*.jpg'
"""
# 确保目标目录存在
Path(target_dir).mkdir(parents=True, exist_ok=True)
# 查找匹配的文件
files = glob.glob(os.path.join(source_dir, pattern))
moved_count = 0
for file_path in files:
try:
# 构建目标路径
file_name = os.path.basename(file_path)
target_path = os.path.join(target_dir, file_name)
# 移动文件
shutil.move(file_path, target_path)
print(f"已移动: {file_path} -> {target_path}")
moved_count += 1
except Exception as e:
print(f"移动失败 {file_path}: {e}")
print(f"\n共成功移动 {moved_count} 个文件")
return moved_count
# 使用方法
source = './downloads'
target = './archived_files'
move_files_with_pattern(source, target, '*.pdf')
按文件类型分类迁移
import shutil
import os
from pathlib import Path
def organize_files_by_extension(source_dir, target_base_dir):
"""
按文件扩展名分类移动到不同文件夹
"""
# 文件类型分类
file_categories = {
'documents': ['.pdf', '.doc', '.docx', '.txt'],
'images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp'],
'videos': ['.mp4', '.avi', '.mkv', '.mov'],
'music': ['.mp3', '.wav', '.flac', '.aac'],
'archives': ['.zip', '.rar', '.tar', '.gz'],
}
# 创建目标目录
for category in file_categories:
Path(os.path.join(target_base_dir, category)).mkdir(parents=True, exist_ok=True)
# 处理文件
for file_name in os.listdir(source_dir):
file_path = os.path.join(source_dir, file_name)
if os.path.isfile(file_path):
# 获取文件扩展名
ext = os.path.splitext(file_name)[1].lower()
# 查找对应的分类
target_folder = None
for category, extensions in file_categories.items():
if ext in extensions:
target_folder = category
break
# 如果没找到分类,放到其他
if not target_folder:
target_folder = 'others'
Path(os.path.join(target_base_dir, 'others')).mkdir(exist_ok=True)
# 移动文件
target_path = os.path.join(target_base_dir, target_folder, file_name)
# 处理同名文件
counter = 1
while os.path.exists(target_path):
name, extension = os.path.splitext(file_name)
target_path = os.path.join(target_base_dir, target_folder, f"{name}_{counter}{extension}")
counter += 1
shutil.move(file_path, target_path)
print(f"已移动 {file_name} -> {target_folder}/")
# 使用示例
organize_files_by_extension('./downloads', './organized_files')
带进度显示的文件移动
import shutil
import os
from pathlib import Path
import time
def move_files_with_progress(source_dir, target_dir, file_pattern='*.*'):
"""
移动文件并显示进度
"""
source_path = Path(source_dir)
target_path = Path(target_dir)
# 获取所有要移动的文件
files_to_move = list(source_path.glob(file_pattern))
total_files = len(files_to_move)
if total_files == 0:
print("没有找到匹配的文件")
return
print(f"发现 {total_files} 个文件需要移动")
# 创建目标目录
target_path.mkdir(parents=True, exist_ok=True)
for i, file in enumerate(files_to_move, 1):
if file.is_file():
try:
# 显示进度
percent = (i / total_files) * 100
print(f"\r进度: [{i}/{total_files}] {percent:.1f}% - 正在移动: {file.name}", end='')
# 移动文件
dest = target_path / file.name
# 处理重名文件
if dest.exists():
name = file.stem
ext = file.suffix
counter = 1
while dest.exists():
dest = target_path / f"{name}_{counter}{ext}"
counter += 1
shutil.move(str(file), str(dest))
time.sleep(0.1) # 模拟进度显示
except Exception as e:
print(f"\n移动失败 {file.name}: {e}")
print(f"\n完成!共移动 {total_files} 个文件")
# 使用示例
move_files_with_progress('./temp', './archive', '*.txt')
文件移动工具类
import shutil
import os
from pathlib import Path
from typing import List, Optional
class FileMover:
"""文件移动工具类"""
def __init__(self, source_dir: str, target_dir: str):
self.source_dir = Path(source_dir)
self.target_dir = Path(target_dir)
self.moved_count = 0
self.error_count = 0
def move_single_file(self, filename: str,
new_name: Optional[str] = None) -> bool:
"""移动单个文件"""
source = self.source_dir / filename
target = self.target_dir / (new_name or filename)
try:
self._ensure_target_dir()
source.rename(target) if source.parent == self.source_dir else shutil.move(str(source), str(target))
self.moved_count += 1
return True
except Exception as e:
print(f"移动失败 {filename}: {e}")
self.error_count += 1
return False
def move_by_pattern(self, pattern: str) -> int:
"""按模式移动文件"""
self._ensure_target_dir()
for file in self.source_dir.glob(pattern):
if file.is_file():
self.move_single_file(file.name)
return self.moved_count
def move_all(self, exclude: List[str] = None) -> int:
"""移动所有文件"""
exclude = exclude or []
self._ensure_target_dir()
for file in self.source_dir.iterdir():
if file.is_file() and file.name not in exclude:
self.move_single_file(file.name)
return self.moved_count
def _ensure_target_dir(self):
"""确保目标目录存在"""
self.target_dir.mkdir(parents=True, exist_ok=True)
def get_status(self) -> dict:
"""获取移动状态"""
return {
'moved': self.moved_count,
'errors': self.error_count,
'source': str(self.source_dir),
'target': str(self.target_dir)
}
# 使用示例
# mover = FileMover('./source', './target')
# mover.move_by_pattern('*.py')
# mover.move_all(exclude=['important.txt', 'config.json'])
# print(mover.get_status())
使用建议
- 权限检查:确保有源文件的读取权限和目标目录的写入权限
- 错误处理:总是用try-except包裹文件操作
- 重名处理:注意处理目标已存在的同名文件
- 备份考虑:重要的文件迁移前先备份
- 日志记录:记录移动日志便于追踪
这些案例覆盖了从简单到复杂的文件迁移场景,可以根据实际需求选择和修改使用。