【问题标题】:How do i remove a specific element/text from an file?如何从文件中删除特定元素/文本?
【发布时间】:2022-01-13 21:41:41
【问题描述】:

我不知道我缺少什么,但我似乎无法删除 .txt 文件中的特定单词,我尝试了 .remove(),但我也收到了错误。

if ans == "remove":
    x = input("Clean sheet or some particular?")

    if x == "whole":
        lista.close()
        os.remove("testsamling.txt")
    if x == "some":
        lista = open("testsamling.txt","r")
        print(lista.read())
        ans = input("Which one?")
        
        lista.truncate.index(ans)
        print("has been removed!")

【问题讨论】:

    标签: python string


    【解决方案1】:

    您可以在“一些”x 选项中执行的操作是使用replace 方法从str 中删除单词并将空字符串作为第二个参数传递给它。

    with open("testsamling.txt","r") as f:
       s = f.read()
       updated = s.replace(ans, '')
    

    然后您可以使用以下命令保存文件:

    with open("testsamling.txt","w") as f:
       f.write(updated)
    

    【讨论】:

      【解决方案2】:

      os.remove 将删除文件。

      你正在寻找的是类似的东西,

      element_to_remove_from_text_file = 'cat '
      file_path = r'C:\my_file.txt'
      
      with open(file_path, mode='r+') as f:
          contents = f.read()
          contents = contents.replace(element_to_remove_from_text_file, '')
          f.seek(0)
          f.write(contents)
      

      【讨论】:

      • 我认为这需要f.seek(0) 在f.write 之前。否则它将在文件末尾追加内容。
      • @LukaszWiecek 你是对的!
      【解决方案3】:

      使用string.replace() 方法:

      • 打开文字:with open(file_path, mode="r") as f
      • 使文件在 python 中可读:source_text = f.read()
      • 用空字符串替换文本:updated_text = source_text.replace(oldtext, "")
      • 将输出写入新文件:
        with open(new_file_path, mode="w" as f):
            f.write(updated_text)
        

      我继续使用click (https://click.palletsprojects.com/en/8.0.x/) 为这样的任务编写了一个小cli(只是我懒得使用外部文件,只是分配了一些随机文本到source_text 变量:

      import click
      
      source_text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt \
        esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, \
        sunt in culpa qui officia deserunt mollit anim id est laborum."
      
      @click.command()
      @click.option("--to_remove", default=None, prompt="What do you want to delete ?", help="The text you want to remove")
      def remove_text(to_remove):
          if str(to_remove) in source_text:
              updated_text = source_text.replace(to_remove, " ")
              click.echo(updated_text)
          else:
              click.echo("Your input is not in the text and could not be deleted")
      
      if __name__ == "__main__":
          remove_text()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-24
        • 1970-01-01
        • 2020-03-05
        • 1970-01-01
        相关资源
        最近更新 更多