Python批量处理指定路径下所有文件
主要函数foreach_file
1 | #!/usr/bin/env python |
应用
利用这个函数就可以方便地处理文件了
打印所有文件名
1
2
3
4source_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
12source_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)
相关文章