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/n7gR 著作权归作者所有。请勿转载和采集!