【问题标题】:Saving user inputs so that they appear again - python 3.2保存用户输入以便它们再次出现 - python 3.2
【发布时间】:2014-12-31 17:47:20
【问题描述】:

我正在尝试保存我的用户输入,但是,当我尝试这样做时,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))

基本上,我希望显示用户输入,但这并没有发生。有人可以向我解释为什么以及我需要做些什么来解决它吗? 问候

【问题讨论】:

标签: python user-input saving-data


【解决方案1】:

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

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

请注意,这会在写入之前将您的文件清空。如果您需要追加到文件末尾,请改用'a' ('append') 模式。

【讨论】:

  • 谢谢,但是我只是尝试使用 'a' 表示追加,现在突然之间,解释器上一个接一个地显示了一个完整的不同符号和字母列表。我再次取出了追加,但它仍然继续发生
  • @0123456 file_obj.write 返回写入 as per the docs 的字符串中的字符数。你可以放心地忽略这些,因为你在解释器中运行,或者只是将它们分配给一个未使用的变量(例如_ = nf.write("\n".join(tempword))
  • @0123456 请注意,这与使2+2 在解释器中向您显示4 相同,但是从控制台运行相同的代码不会显示任何输出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-09-17
  • 1970-01-01
  • 1970-01-01
  • 2020-09-14
  • 2021-07-17
  • 2021-12-25
  • 1970-01-01
相关资源
最近更新 更多