无法使用 open() 写入文件

Cannot write to a file using open()

这段代码总是进入例外部分

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")

以 'w' 而非 'r'

打开文件
with open('test.txt', 'w') as txt:

需要进行一些修复。

试试这个片段:

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")