Python递归遍历目录并删除文件中的前N行

 1 import os
 2 
 3 # 遍历目录下的所有文件
 4 def check_file(file_path):
 5     os.chdir(file_path)
 6     print(os.path.abspath(os.curdir))
 7     all_file = os.listdir()
 8     files = []
 9     for f in all_file:
10         if os.path.isdir(f):
11             files.extend(check_file(file_path+'\\'+f))
12             os.chdir(file_path)
13         else:
14             # files.append(f)
15             files.append(os.path.abspath(f))
16     return files
17 
18 
19 # 删除前N行
20 def delete_line(file_path):
21     with open(file_path, 'r', encoding='utf-8') as f:
22         lines = f.readlines()[15:]
23 
24     with open(file_path, 'w', encoding='utf-8') as f:
25         for line in lines:
26             f.write(line)
27         
28 
29 file_list = check_file("D:/workspace/soas-console/src/main/java/com/soa/supervision/admin")
30 for i in file_list:
31     print(i)
32     delete_line(i)
posted @ 2022-02-28 17:36  废物大师兄  阅读(408)  评论(0编辑  收藏  举报