Python批量处理指定路径下所有文件

主要函数foreach_file

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env python
# -*-coding:utf-8 -*-

import os
from typing import Callable


def foreach_file(path: str, do: Callable[[str], None]):
"""处理路径下所有文件

:param path: 起始目录
:param do: 文件处理函数(参数为绝对路径,无返回值)
:return: 无返回值
"""
files = os.listdir(path)
for file in files:
file_abs = os.path.join(path, file)
if os.path.isdir(file_abs):
foreach_file(file_abs, do)
else:
do(file_abs)

应用

利用这个函数就可以方便地处理文件了

  • 打印所有文件名

    1
    2
    3
    4
    source_path = 'D:/test/'

    if __name__ == '__main__':
    foreach_file(source_path, lambda file: print(file))
  • 更改文件后缀

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    source_path = 'D:/test/'

    def process(file: str):
    root_ext = os.path.splitext(file)
    if root_ext[1] == '.txt': # 将所有.txt文件改为.data
    new_name = root_ext[0] + '.data'
    # print(file + ' --> ' + new_name)
    os.rename(file, new_name)


    if __name__ == '__main__':
    foreach_file(source_path, process)