py_gadgets/rm_lines.py
2024-09-13 18:23:55 +08:00

27 lines
987 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
def remove_first_n_lines_from_files(directory, n):
for filename in os.listdir(directory):
filepath = os.path.join(directory, filename)
if os.path.isfile(filepath):
with open(filepath, 'r+', encoding='utf-8') as file:
lines = file.readlines()
# 检查文件的行数是否多于n
if len(lines) > n:
# 删除前n行
lines = lines[n:]
else:
# 如果文件行数少于等于n将其内容清空
lines = []
# 回到文件开头,写入处理后的内容
file.seek(0)
file.writelines(lines)
# 截断文件以删除多余的内容
file.truncate()
# 示例用法
directory = r'C:\Users\anenvoy\Desktop\notes' # 修改为你的实际文件夹路径
n = 6 # 要删除的行数
remove_first_n_lines_from_files(directory, n)