【问题标题】:Cannot write to a file using open()无法使用 open() 写入文件
【发布时间】:2023-04-01 18:08:01
【问题描述】:

此代码总是进入 except 部分

to_add = "text to add"
try:
    with open ('text.txt','r') as txt:
        txt.write('text to add'+to_add')
        print("done")
    except:
        to_add== 0 or None or '' 
        print("unable to write to file")

【问题讨论】:

  • 这里有一个额外的报价txt.write('text to add'+to_add')。删除最后一个。
  • 请正确格式化您的代码,click here to learn how
  • 要写入文件,请使用open(file_name, 'w') 或附加open(file_name, 'a')。您已使用 'r' 选项以读取模式打开它。

标签: python python-3.x with-statement


【解决方案1】:

以“w”而不是“r”打开文件

with open('test.txt', 'w') as txt:

【讨论】:

    【解决方案2】:

    需要进行一些修复。

    试试这个 sn-p:

    to_add = "text to add"
    try:
      with open ('text.txt', 'w') as txt:    # change the mode to write 
          txt.write('text to add' + to_add)  # removing the last char '
      print("done")
    except NameError:  
      print("unable to write to file")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-13
      • 2016-10-20
      • 2012-10-16
      • 2014-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多