import os
import re
# 获取Python脚本所在的目录
directory = os.path.dirname(os.path.realpath(__file__))
# 遍历目录及其所有子目录下的所有文件
for root, dirs, files in os.walk(directory):
for filename in files:
# 如果文件是.srt文件
if filename.endswith('.srt'):
path = os.path.join(root, filename)
with open(path, 'r', encoding='utf-8') as file:
lines = file.readlines()
# 移除空白行
new_lines = [line for line in lines if not re.match(r'^\s*$', line)]
# 将处理过的行写回文件
with open(path, 'w', encoding='utf-8') as file:
file.writelines(new_lines)
-------------------------------------------------------------------------------------------------------
import os
import re
def insert_blank_line(filename):
with open(filename, 'r', encoding='utf-8') as file:
lines = file.readlines()
new_lines = []
for line in lines:
if re.match(r'^[1-9]\d*', line.strip()):
new_lines.append('\n')
new_lines.append(line)
with open(filename, 'w', encoding='utf-8') as file:
file.writelines(new_lines)
def find_srt_files(path):
for root, dirs, files in os.walk(path):
for file in files:
if file.endswith('.srt'):
insert_blank_line(os.path.join(root, file))
if __name__ == "__main__":
find_srt_files('.')