Python删除CSV行而不创建新文件 [英] Python delete CSV row without creating a new file

查看:78
本文介绍了Python删除CSV行而不创建新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Python(Raspberry Pi)编辑CSV文件.我使用"append"标签打开文件并添加一行.之后,我检查fil的大小.如果文件太大,我想删除数据的第一行(有标题行).我看到的每个示例都将跳过该行,并将所有其他行写入不同的CSV文件.我不想创建一个新的CSV文件...我只想删除当前文件的第一行并保存它.

I am using Python (Raspberry Pi) to edit a CSV file. I open the file with the "append" tag and add a line. After that I check the size of the fil. If the file size is too big, I want to delete the first row of data (there is a headers row). Every example I see just skips the row and the writes all the other rows to a different CSV file. I do not want to have to create a new CSV file...I just want to delete the first row in the current file and save it.

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****

推荐答案

只是一种获得灵感的方法.在这种情况下,无需制作新文件并重命名:

Just a way to do it for inspiration. There is no need to make a new file and rename in this case:

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)])

这篇关于Python删除CSV行而不创建新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆