我使用Python(Raspberry Pi)编辑CSV文件。我用“append”标签打开文件并添加一行。之后我检查了fil的大小。如果文件太大,我想删除第一行数据(有一个标题行)。我看到的每个示例都会跳过该行,并将所有其他行写入不同的CSV文件。我不想创建新的CSV文件...我只想删除当前文件中的第一行并保存它。
import csv
def write_csv(datalist):
with open("CSVfile",'a') as f:
writer = csv.writer(f, delimiter=',' ,quoting=csv.QUOTE_NONE)
writer.writerow(datalist)
while os.path.getsize("CSVfile") > 100000:
****DELETE FIRST ROW OF DATA FROM CSV FILE****
答案 0 :(得分:0)
只是一种灵感来做的方式。在这种情况下,无需创建新文件并重命名:
import csv
import os
import random
def ensure_csv_max_size(size):
# Read all data into memory.
with open('CSVfile', 'r') as f:
reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
csv_data = list(reader)
# Remove first row, save, check repeatedly.
for i in range(len(csv_data)):
with open('CSVfile', 'w') as f:
writer = csv.writer(f, delimiter=',', quoting=csv.QUOTE_NONE)
writer.writerows(csv_data[i:])
print(os.path.getsize('CSVfile'))
if os.path.getsize('CSVfile') <= size:
break
def write_csv(datalist):
with open("CSVfile",'a') as f:
writer = csv.writer(f, delimiter=',' ,quoting=csv.QUOTE_NONE)
writer.writerow(datalist)
while os.path.getsize("CSVfile") > 100000:
print("cut")
ensure_csv_max_size(100000)
for i in range(1000):
write_csv([random.randint(0, 100) for _ in range(10)])