繁体   English   中英

当我在 Python 中写入 CSV 文件时,它会复制最后一行的一部分并将其写入文件底部

[英]When I write to a CSV file in Python, it copies part of the last row and writes it to the bottom of the file

我正在将用户数据保存到 CSV 文件。 当我尝试更新用户信息时,信息会正确更新,但它还会复制最后一行的最后几个字符,创建一个新行并将其粘贴。

这是我的代码

(索引和新索引是列表行中有 2 个不同用户的索引)

with open(filename,'r+',newline='') as f:
    reader = csv.reader(f)
    lines = list(reader)


with open(filename,'r+',newline='') as f:

    writer = csv.writer(f)
    lines[index][3]= inv
    lines[index][2] = money

    lines[newindex][2] = sellermoney
    lines[newindex][8] = shopitems
    writer.writerows(lines)

    f.close()

提前致谢

那是因为您的open函数的mode误用了。

r+更新文件内容。 因此,如果新的内容尺寸较小,则之前的内容将保留。

所以, w应该在你的情况下使用。

了解有关开放功能的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM