用Python写一个将目录里所有文件固定行数内容替换成别的内容的脚本
以下是一个示例脚本,它会将指定目录下所有文件的前两行替换为指定的内容:
import os
dir_path = "/path/to/directory"
new_content = "This is the new content."
for file_name in os.listdir(dir_path):
file_path = os.path.join(dir_path, file_name)
if os.path.isfile(file_path):
with open(file_path, "r") as f:
lines = f.readlines()
if len(lines) >= 2:
lines[0] = new_content + "\n"
lines[1] = new_content + "\n"
with open(file_path, "w") as f:
f.writelines(lines)
需要注意的是,这个脚本并没有进行错误处理,例如目录不存在或者文件不可读写等情况。如果需要在生产环境中使用该脚本,需要添加相应的错误处理机制
原文地址: https://www.cveoy.top/t/topic/fe4x 著作权归作者所有。请勿转载和采集!