Python 如何将整数写入文件.io.UnsupportedOperation:不可写
我正在尝试将1添加到excel中文件的最后一个整数。我可以这样做,因为新的_id是正确的。但是,当我尝试将新的_id写入文件时,它不起作用。返回Python 如何将整数写入文件.io.UnsupportedOperation:不可写,python,csv,input,output,Python,Csv,Input,Output,我正在尝试将1添加到excel中文件的最后一个整数。我可以这样做,因为新的_id是正确的。但是,当我尝试将新的_id写入文件时,它不起作用。返回io。不支持操作:不可写错误消息。 导入csv ID=[] 文件=打开(“customerID.csv”、“r”) 对于文件中的x: ID.append(x) lastid=int(ID[-1]) new_id=(lastid+1) file.close 打印(lastid) 打印(新id) file.write(str(新的_id)) file.clo
io。不支持操作:不可写错误消息。
导入csv
ID=[]
文件=打开(“customerID.csv”、“r”)
对于文件中的x:
ID.append(x)
lastid=int(ID[-1])
new_id=(lastid+1)
file.close
打印(lastid)
打印(新id)
file.write(str(新的_id))
file.close
当您在打开
中指定了'r'
时,您打开的文件仅用于阅读。如果你想能够写作,你需要打开它进行写作。如果要写入文件末尾(追加),请使用'a'
;如果要在写入之前擦除文件,请使用'w'
:
file = open("customerID.csv", "a")
还要注意,您的
文件.close
行没有任何作用。您需要实际调用close
方法:
file.close() # Note the ()
而且,一旦调用了
close
,您就不能使用file
。非常感谢,我现在觉得自己很愚蠢。我想它只需要另一双眼睛。