【问题标题】:Code that removes a certain word from a txt file in python从python中的txt文件中删除某个单词的代码
【发布时间】:2021-06-01 11:28:41
【问题描述】:

我目前正在创建一个程序,该程序允许用户向 txt 文件中的单词列表添加或删除任何单词,但是,我在删除用户从所述文本文件中请求的某些单词时遇到问题。这是我的代码(忽略其他部分):

from test_words import word_list
test_list=open('test_words.txt')
test_list=test_list.read().splitlines()

def changewords():
    morewords=input('Would you like to change the word list?(Y/N)\n').upper()
    if morewords=='Y':
        which=input('Add, Delete, Clear or Reset?(A/D/C,R)\n').upper()
        if which=='A':
            add=input('What word would you like to add?\n')
            file=open('test_words.txt','a')
            file.write('\n')
            file.write(add)
            file.close()
            changewords()
        elif which=='D':
            remove=input('what word would you like to remove?\n')
            ???????
            file.close()
            changewords()
        elif which=='C':
            file=open('test_words.txt','w')
            file.write('')
            file.close()
            changewords()
        elif which=='R':
            file=open('test_words.txt','w')
            file.write('\n'.join(word_list))
            file.close()
            changewords()
        else:
            print('Incorrect input')
            changewords()
changewords()

感谢您的帮助

【问题讨论】:

  • 那么您现在面临的问题是什么?
  • 你可以test_list.remove(remove)然后再写test_list文件。

标签: python file text txt


【解决方案1】:

我假设您不想修改 test_list,因为这是文件的原始内容,在用户请求“重置”文件时需要保持不变。

要删除请求的单词,您可以打开并阅读文件的内容。用空白文本替换任何出现的单词。然后写回文件。

file=open('test_words.txt','r')         # Open the file in read mode
fileText = file.read()                  # Read in the contents to a string variable
file.close()                            # Close the file as you cant write to it in read mode
fileText = fileText.replace(remove, '') # Replace any occurances of the word the user wants to remove with a blank string
file=open('test_words.txt', 'w')        # Open the file again, but this time in write mode
file.write(fileText)                    # Write the modified text back to the file
file.close()                            # Close the file

搜索堆栈溢出似乎已经有了这个问题的答案: How to search and replace text in a file?

【讨论】:

  • 抱歉没用,出现此错误:回溯(最近一次调用最后一次):文件“我的文件”,第 39 行,在 changewords() 文件“我的文件”,行22、在changewords file.open('test_words.txt','w') AttributeError: '_io.TextIOWrapper' object has no attribute 'open'
  • @Qu1ppy,我错过了输入。将file.open('test_words.txt,'w') 替换为file=open('test_words.txt,'w')。我也会更新答案。
猜你喜欢
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多