仅读取CSV文件第一行的代码

2024-07-04 08:54:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想读取CSV文件每行的第一列,以便尝试找到一个值。目前我有:

def checkForCable(idNum):
    with open("test.txt") as csv_file:
        csv_reader = csv.reader(csv_file, delimiter=',')
        for row in csv_reader:
            if row[0] == idNum:
                print("matching barcode found")
                return True
            else:
                print("barcode not on file. Adding...")
                return False

但这似乎只是检查第一行的第一列,然后停止,而不是检查CSV文件中n行的所有第一列。例如,如果第0列中的行[0]不等于它要搜索的数字,那么它将不会继续检查第1列中的行[0],我不确定原因


Tags: 文件csvtestreturndefwithopenbarcode
2条回答

你可以用熊猫。熊猫在处理csv文件方面非常出色

import Pandas as pd

file = pd.read_csv('csv_file')
df = pd.DataFrame(file)

# Check if Dataframe is empty using empty attribute
if df['Columnname'].empty == True:
    print('Barcode is empty')
else:
    print('Barcode is not empty')

关于守则:

for row in csv_reader:
    if row[0] == idNum:
        print("matching barcode found")
        return True
    else:
        print("barcode not on file. Adding...")
        return False

如果您允许,这个for循环确实会处理每一行,但是您不允许它,因为if语句的真部分和假部分在读取第一行后返回,实际上忽略了所有其他部分


您可能需要的是这个方案:如果您在第一行中没有找到它,不要立即返回false-您需要检查所有其他行,并且只有在没有行时才返回false

换句话说,类似这样的事情:

# Check ALL rows.

for row in csv_reader:
    # If found in THIS row, notify success.

    if row[0] == idNum:
        print("matching barcode found")
        return True

# If found in NO rows, notify failure.

print("barcode not on file. Adding...")
return False

相关问题 更多 >

    热门问题