【问题标题】:Deleting contents of file after a specific line in python [closed]在python中的特定行之后删除文件的内容[关闭]
【发布时间】:2020-04-15 12:43:57
【问题描述】:

我有一个这种格式的文件:

22||512|6682,4865,4866,49200,52393,52392,49171,53,10|354,0,16,5,13,18,51,45,43,27,10794,21|14906
22,20||122,1|4865|51,43|29
|23|2064|||
20|23|1,53|||
|23|87|||
|23|322|||
|23,23|445,66|||
|23|26|||

我想删除“20|23|1,53|||”行下方的所有行
我不知道如何在 python 中做到这一点

【问题讨论】:

  • 从文件中读取,然后写入行,直到到达该行。如果您希望它健壮(没有数据丢失),您应该使用单独的输入和输出文件执行此操作,然后使用mv 原子覆盖。

标签: python file


【解决方案1】:

answer 中使用截断

with open('test.txt', 'r+') as file:
  line = file.readline()
  while line:
      if line.rstrip() == '20|23|1,53|||':
          file.truncate(file.tell()) # tell returns current position of file read/write pointer
          break
      line = file.readline()

【讨论】:

    【解决方案2】:
    text=""
    with open("file.txt", "r") as f:
        text = f.read()
    with open("file.txt", "w") as f:
        f.write( text[ : text.find("20|23|1,53|||") ] )
    

    首先,我们读取 file.txt 的内容并将其移动到变量 text 中。 然后,我们使用 text.find 查找字符串“20|23|1,53|||”的位置位于(它将返回它所在位置的索引) 最后,我们用文本变量中除“20|23|1,53|||”之外的所有内容覆盖 file.txt 的内容(以及之后的内容)。

    【讨论】:

      猜你喜欢
      • 2023-04-07
      • 1970-01-01
      • 2022-12-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-05-01
      相关资源
      最近更新 更多