【问题标题】:How to write integer to a file,.io.UnsupportedOperation: not writable如何将整数写入文件,.io.UnsupportedOperation:不可写
【发布时间】:2020-02-10 08:51:14
【问题描述】:

我正在尝试将 1 添加到 excel 中文件的最后一个整数。我可以这样做,因为 new_id 是正确的。但是,当我尝试将 new_id 写入文件时,它不起作用。返回io.UnsupportedOperation: not writable error message.

import csv
ID = []

file = open("customerID.csv","r")

for x in file:
    ID.append(x)

lastid = int(ID[-1])

new_id = (lastid + 1)

file.close
print(lastid)
print (new_id)

file.write (str(new_id))

file.close

【问题讨论】:

    标签: python csv input output


    【解决方案1】:

    当您在open 中指定'r' 时,您才打开文件进行读取。如果你想能够写,你需要打开它来写。如果您想写入文件末尾(追加),请使用'a',如果您想在写入之前擦除文件,请使用'w'

    file = open("customerID.csv", "a")
    

    另外请注意,您的 file.close 行没有做任何事情。您需要实际调用close 方法:

    file.close()  # Note the ()
    

    而且,一旦close 被调用,你就不能使用file

    【讨论】:

    • 非常感谢,我现在觉得自己很愚蠢。我想它只是需要另一双眼睛。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多