首页 > 解决方案 > 为什么我在 csv 上的最后一个数据会被 python 删除

问题描述

我是 python 新手,我正在写一些 CSV 项目,但是每次运行它都会删除我的最后一个数据并编写一个新数据,这就是代码

with open('data.csv', 'w', newline='')as f:
    User_new_pass = input('enter your new password: ').strip()
    User_new_id = ' ' + input('enter your new user name: ').strip()
    User_new_info = [User_new_pass, User_new_id]
    linewriter = csv.writer(f)
    linewriter.writerow(User_new_info)

标签: pythonpython-3.xcsv

解决方案


如果要附加到文件,则应更改open()函数中的模式:

with open('data.csv', 'a', newline='')as f:
    # your code

a-Open file in append mode. If file does not exist, it creates a new file.

w-This Mode Opens file for writing. If file does not exist, it creates a new file. If file exists it truncates the file.


推荐阅读