👉 项目官网:https://www.python-office.com/ 👈

github star

大家好,这里是程序员晚枫,正在all in AI编程实战

今天教你怎么批量操作大量文件——重命名、压缩、复制、移动,一键搞定。

1、遍历文件夹里的所有文件

1
2
3
4
5
6
import os

folder = '文件夹路径'

for file in os.listdir(folder):
print(file)

遍历包括子文件夹:

1
2
3
4
5
6
import os

for root, dirs, files in os.walk('文件夹路径'):
for file in files:
filepath = os.path.join(root, file)
print(filepath)

2、批量复制文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import shutil
import os

src_folder = '源文件夹'
dst_folder = '目标文件夹'

os.makedirs(dst_folder, exist_ok=True)

for file in os.listdir(src_folder):
src = os.path.join(src_folder, file)
dst = os.path.join(dst_folder, file)
shutil.copy(src, dst)
print(f'已复制: {file}')

print(f'共复制 {len(os.listdir(src_folder))} 个文件')

3、批量移动文件

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

folder = '文件夹'

for file in os.listdir(folder):
if file.endswith('.tmp'): # 只移动临时文件
src = os.path.join(folder, file)
dst = os.path.join('回收站', file)
shutil.move(src, dst)
print(f'已移动: {file}')

4、批量删除文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import os

folder = '文件夹'

for file in os.listdir(folder):
if file.endswith('.bak'): # 删除所有.bak备份文件
path = os.path.join(folder, file)
os.remove(path)
print(f'已删除: {file}')

# 删除空文件夹
for folder in os.listdir('.'):
path = os.path.join('.', folder)
if os.path.isdir(path) and not os.listdir(path):
os.rmdir(path)
print(f'已删除空文件夹: {folder}')

5、批量压缩文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import zipfile
import os

def batch_zip(folder, output_name):
"""批量压缩文件夹"""
with zipfile.ZipFile(output_name, 'w', zipfile.ZIP_DEFLATED) as zipf:
for root, dirs, files in os.walk(folder):
for file in files:
filepath = os.path.join(root, file)
arcname = os.path.relpath(filepath, folder)
zipf.write(filepath, arcname)
print(f'已添加: {arcname}')

print(f'压缩完成: {output_name}')

# 压缩整个文件夹
batch_zip('要压缩的文件夹', '压缩包.zip')

6、批量解压文件

1
2
3
4
5
6
7
8
9
import zipfile
import os

zip_file = '压缩包.zip'
extract_folder = '解压目录'

with zipfile.ZipFile(zip_file, 'r') as zipf:
zipf.extractall(extract_folder)
print(f'已解压到: {extract_folder}')

7、实战案例:整理下载文件夹

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
import os
import shutil

def organize_downloads():
"""整理下载文件夹"""
downloads = 'C:\\Users\\你的用户名\\Downloads'

# 定义分类规则
categories = {
'Images': ['.jpg', '.jpeg', '.png', '.gif', '.bmp'],
'Documents': ['.pdf', '.doc', '.docx', '.xlsx', '.xls', '.pptx'],
'Videos': ['.mp4', '.avi', '.mov', '.mkv'],
'Music': ['.mp3', '.wav', '.flac'],
'Archives': ['.zip', '.rar', '.7z'],
'Others': [] # 其他文件
}

# 创建分类文件夹
for category in categories:
path = os.path.join(downloads, category)
os.makedirs(path, exist_ok=True)

# 移动文件
moved = 0
for file in os.listdir(downloads):
filepath = os.path.join(downloads, file)

# 跳过文件夹
if os.path.isdir(filepath):
continue

# 确定分类
ext = os.path.splitext(file)[1].lower()
target_folder = 'Others'

for category, extensions in categories.items():
if ext in extensions:
target_folder = category
break

# 移动文件
target = os.path.join(downloads, target_folder, file)
shutil.move(filepath, target)
moved += 1
print(f'{file} -> {target_folder}')

print(f'\n整理完成!共移动 {moved} 个文件')

organize_downloads()

8、常见问题

Q:删除文件后能恢复吗?

A:建议用 shutil.move 移动到"回收站"文件夹,而不是直接删除。

Q:压缩后文件太大?

A:用 zipfile.ZIP_DEFLATED 压缩率更高。

Q:文件名有中文会乱码?

A:Python 3 默认支持 UTF-8,尽量用英文文件名。

9、下讲预告

学会了批量处理文件,下一讲我们学 网页数据抓取:自动获取网上数据。

敬请期待!


有问题欢迎加微信 python-office 进群交流~

程序员晚枫专注AI编程培训,小白看完他和图灵社区合作的教程《30讲 · AI编程训练营》就能上手做AI项目。

🎓 AI 编程实战课程

想系统学习 AI 编程?程序员晚枫的 AI 编程实战课 帮你从零上手!