簡體   English   中英

如何從文件中刪除特定元素/文本?

[英]How do i remove a specific element/text from an file?

我不知道我缺少什么,但我似乎無法刪除 an.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!")

您可以在“some” 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)

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)

使用string.replace()方法:

  • 打開文本: with open(file_path, mode="r") as f
  • 使文件在 python 中可讀: source_text = f.read()
  • 用空字符串替換文本: updated_text = source_text.replace(oldtext, "")
  • 將 output 寫入新文件:
     with open(new_file_path, mode="w" as f): f.write(updated_text)

我繼續使用clickhttps://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()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM