Python在操作.txt文件,使文件每行开头添加上 “#”,变成如图中所示的格式。

问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
运行结果及报错内容
我的解答思路和尝试过的方法
我想要达到的结果

img

先读出,再遍历每一行,加上#后写入文件

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)