先读出,再遍历每一行,加上#后写入文件
with open('12.txt', 'r', encoding='utf-8') as fn:
lines = fn.readlines()
with open('12.txt', 'w', encoding='utf-8') as fn:
for line in lines:
fn.write('#'+line)
with open("./12.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
with open("./12.txt", "w", encoding="utf-8") as f1:
for ln in lines:
if "#" != ln[0]: #判断每行第一个字符是不是# ,存在就不改变,不存在就添加
f1.write("#"+ln)
else:
f1.write(ln)