简体   繁体   English

添加新行而不覆盖现有行

[英]Adding new row without overwriting existing row

I have a problem with writing dataframe to csv.我在将数据帧写入 csv 时遇到问题。 So this is my code所以这是我的代码

sent_ts = int(request.headers['ts'])
recv_ts = int(round(time.time() * 1000))
call_ts = recv_ts - sent_ts

ts_list = {'sent_ts':[sent_ts], 'callback':[call_ts]}

df = pd.DataFrame(ts_list, columns = ['sent_ts', 'callback'])
df.to_csv('timestamp.csv', index = False)
print(df)

So when I executing the python script more than one times, it overwriting existing data not make a new row.因此,当我多次执行 python 脚本时,它会覆盖现有数据而不是创建新行。 How do I make a new row when every time I'm executed the python script?每次执行python脚本时如何创建新行? Thanks in advance !提前致谢 !

Open the file in append mode, and write the new row to that file.以追加模式打开文件,并将新行写入该文件。

with open('timestamp.csv', 'a', newline = '') as f:
    df.to_csv(f, index = False, header = False)

header = False will prevent it from adding a header line each time you write a row. header = False将阻止它在每次写入行时添加标题行。

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

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