检查CSV的第一个单元格在Python中是否为空白 [英] Checking if the first cell of a CSV is blank in Python

查看:261
本文介绍了检查CSV的第一个单元格在Python中是否为空白的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将字典编写为CSV.它处于循环中,因此循环中的每次迭代都应将最新字典附加到CSV的末尾.

I'm trying to write a dictionary to a CSV. It's in a loop so each iteration through the loop should append the latest dictionary to the end of my CSV.

我想添加一个仅在文件为空白时才将标头写入CSV的功能.

I wanted to add a feature where I only write the header to the CSV if the file is blank.

我尝试使用f.tell()检查它是否在第一个位置,但似乎不一致.我删除所有内容并将光标设置到第一个单元格并保存文件,它有时会返回2,其他会返回0.

I've tried to use f.tell() to check if it's in the first position but it doesn't seem to be consistent. I delete everything and set the cursor to the first cell and save the file and it'll return 2 sometimes and 0 others.

我当时正在考虑将数据更改为这样的列表,以便可以执行data[1][0]:

I was thinking of changing the data to a list like this so I can just do data[1][0]:

data=list(csv.reader(csvDataFile))

,然后使用if语句查看第一个位置是否为空,但感觉效率低下(如果不是,请让我知道,我会坚持下去).这是这里的代码段.有没有更有效,更清晰的方法来做到这一点?

and then using an if statement to see if the first position is empty but that feels inefficient (if it's not, then just let me know and I'll stick with that). This is code snippet here. Is there a more efficient and clear way to do this?

with open('DataOutput.csv', 'a', newline='') as f:
    writer = csv.DictWriter(f, sorted_closes.keys())
    print(f.tell())
    if f.tell() == 0:
        writer.writeheader()
        writer.writerow(sorted_closes)
    else:
        writer.writerow(sorted_closes)

我的解决方案:

万一任何人遇到相同的问题.我最终仅使用try/except来处理文件为空的情况.

In case anyone encounters the same problem. I ended up just using a try/except to handle the case where the file was empty.

因为newline=''会(由于某种原因)在第2行开始我的输出.所有这些建议的方法都无效.如果我在一个空文件中查找从第2行开始的行,它将抛出IndexError.如果我尝试使用csv.Sniffer.has_header方法,它将永远不会返回True,因为标题始终位于第2行.

Because newline='' would (for some reason) start my output on line 2. None of these proposed methods worked. If I looked for the row beginning at line 2 in an empty file, it would throw an IndexError. If i tried the csv.Sniffer.has_header approach, it would never return True because the header was always on line 2.

无论如何,这最终对我有用.不知道这是否是最有效的方法,但它是否有效:

Anyway, this eventually worked for me. Not sure if its the most efficient way but it worked:

    with open(filename + '.csv', 'a', newline='') as csv_a, open(filename + '.csv','r', newline='') as csv_r:
        reader = csv.reader(csv_r)
        writer = csv.DictWriter(csv_a, dict.keys())
        data = [row for row in reader]

        try:
            first_row_blank = True if data[1] == [] else False

        except IndexError:
            first_row_blank = True

        if first_row_blank:
            writer.writeheader()
            writer.writerow(dict)
        else:
            writer.writerow(dict)

推荐答案

我能够使它起作用:

with open('some_file.csv', 'a', newline='') as csv_a, open('some_file.csv','r') as csv_r:
    reader = csv.reader(csv_r)
    writer = csv.DictWriter(csv_a, sorted_closes.keys())
    data = [row for row in reader] #turns all the cells into a list
    if data[0][0]=='':
        writer.writeheader()
        writer.writerow(sorted_closes)
        # or whatever you want to do if the first cell is empty
    else:
        writer.writerow(sorted_closes)
        # or whatever you want to do if the first cell is NOT empty

这篇关于检查CSV的第一个单元格在Python中是否为空白的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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