简体   繁体   English

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

[英]Code only reading the first row of a CSV file

I want to read the 1st column of each row of a CSV file in order to try and find a value.我想读取 CSV 文件每一行的第一列,以尝试找到一个值。 Currently I have this:目前我有这个:

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

But this seems to only check the first column of the first row and then stop, rather than checking all of the first columns of the n rows in the CSV file.但这似乎只检查第一行的第一列然后停止,而不是检查 CSV 文件中第 n 行的所有第一列。 For instance if row[0] in column 0 is not equal to the number it's searching for, then it won't proceed to check row[0] in column 1 etc. and I'm not sure why.例如,如果第 0 列中的 row[0] 不等于它正在搜索的数字,那么它不会继续检查第 1 列中的 row[0] 等等,我不知道为什么。

Regarding the code:关于代码:

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

This for loop does indeed process every row if you let it, but you are not letting it because both your true and false parts of the if statement return after reading the first row, effectively ignoring all the others.如果您允许,此for循环确实会处理每一行,但您不会允许它,因为if语句的 true 和 false 部分在读取第一行后都返回,有效地忽略了所有其他行。


What you probably need is this scheme: if you don't find it in the first row, don't immediately return false - you need to check all the other rows and return false only if it's in none of them.你可能需要的是这个方案:如果你没有在第一行找到它,不要立即返回 false - 你需要检查所有其他行,只有当它都不在它们中时才返回 false。

In other words, something like this:换句话说,是这样的:

# 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

You can use Pandas.你可以使用熊猫。 Pandas is very excellent in dealing with csv files. Pandas 在处理 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')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM