保存用户输入以便它们再次出现在python3.2中

2024-06-26 14:34:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试保存用户输入,但是,当我尝试保存时,python shell中出现以下消息:

 nf.write('\n'.join(tempword))
io.UnsupportedOperation: not writable

以下是我的代码:

 clues_list=[]
    userInput=input("Enter a symbol you would like to replace:")
    userInput2=input("What letter would you like to replace it with:")

    for word in words_list:
        tempword = (word)
        tempword = tempword.replace('#','A')
        tempword = tempword.replace('*', 'M')
        tempword = tempword.replace('%', 'N')
        tempword=tempword.replace(userInput,userInput2)
        print(tempword)
        clues_list.append(tempword)
        with open('words.txt', 'r') as nf:# bit that isnt working 
            nf.write('\n'.join(tempword))

基本上,我希望用户输入显示,但这是没有发生。有人能给我解释一下为什么我需要做什么来修复它吗? 敬礼


Tags: to用户youinputreplacelistlikewrite
1条回答
网友
1楼 · 发布于 2024-06-26 14:34:25

看起来您正在以只读方式打开words.txt,然后尝试对其进行写入。请尝试:

with open('words.txt', 'w') as nf:
    nf.write('\n'.join(tempword))

请注意,这将在写入文件之前清空文件。如果需要附加到文件末尾,请改用'a''append')模式。你知道吗

相关问题 更多 >