[英]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.