[英]Python Pandas: how to shift row content on each rows independently to produce Covid chart from the 100th case
[英]Is there any way to delete the 100th row (or 'last row'), from a csv file, as a new row gets added?
有沒有辦法從 csv 文件中刪除最后一行,因為添加了新行? (無需創建單獨/重復的 csv 文件) 。
我的目標是防止正在運行的 csv 文件超過行數和大小。
理想情況下:
我得到的錯誤是:
DictWriter 不可迭代。
並且 DictReader 不會寫入 csv。
import csv, sys, os
filename = "sampletable2.csv"
'''
sampletable2.csv contains :
high, low, precipitation
22, 53, 0.12
33, 52, 0.1
44, 54, 0.1
99, 98, 0.97
'''
new_row = {'high': '99', 'low': '98', 'precipitation': '0.97'}
data = [] # list of dictionaries
max_rows = 4
# READER
with open(filename, 'r', newline='') as csvfile:
csvreader = csv.DictReader(csvfile)
for i, row in enumerate(csvreader):
if i >= max_rows: # =row to chop - 2
del (data[:- max_rows]) # row to chop - 2 del(data[:max_rows]) # row to chop - 2
else:
data.append(row) # continually add pre found rows to new data_dic list.
data.append(new_row) # ALWAYS ADD ((( NEW )) FOUND SINGLE DATA RECORD
csvfile.close()
# WRITER (write while still opened for reading) ; just writes new limited row data to csv
with open(filename, 'w', newline='') as f:
fieldnames = ["high", "low", "precipitation"]
csvwriter = csv.DictWriter(f, fieldnames=fieldnames)
csvwriter.writeheader() # AWAYS WRITE HEADER due to 'w' starts all over ; never use 'a'
csvwriter.writerows(data)
f.close() # not necess but allows to see updated csv if viewing sep monitor real-time
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.