python 删除文件某一行

- 日理万妓 2021-09-02 04:48 632阅读 0赞

文件内容:

  1. Yesterday when I was young
  2. 昨日当我年少轻狂
  3. The tasting of life was sweet
  4. 生命的滋味是甜的
  5. As rain upon my tongue
  6. tasting
  7. I lived by night and shunned the naked light of day
  8. tasting123
  9. And only now I see how the time ran away
  10. tasting
  11. tasting

思路:打开文件后 一行一行写入 需要删除的行 使用continue跳过 不写入

将文本中的 tasting123删除 代码如下:

  1. with open("fileread.txt","r",encoding="utf-8") as f:
  2. lines = f.readlines()
  3. #print(lines)
  4. with open("fileread.txt","w",encoding="utf-8") as f_w:
  5. for line in lines:
  6. if "tasting123" in line:
  7. continue
  8. f_w.write(line)

发表评论

表情:
评论列表 (有 0 条评论,632人围观)

还没有评论,来说两句吧...

相关阅读