您的 csv 文件中可能没有识别号,在这种情况下,由于您的“if”语句,不会打印任何内容。您可以检查您是否找到了该号码,如果是,则中断(如果您不想检查其他行以获取该号码的另一个实例),如果没有,则打印您从未找到该号码。
with open('C:/MAIL07072021180029.csv', 'r') as file:
data = csv.reader(file)
found = False
for row in data:
if row[1] == (identifyingnumber):
print(row)
found = True
break # if you don't want to look for more instances of identifyingnumber
if not found: # aka found == False
print('I did not find any row[1] equal to', identifyingnumber)
我强烈建议您尝试使用 Pandas。在 Pandas 中打开 csv,然后一次检查所有行的值,而不是遍历行。 https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_csv.html
import pandas as pd
df = pd.read_csv('C:/MAIL07072021180029.csv')
col1 = df.columns[1]
dfi = df[df[col1] == identifyingnumber]
dfi = dfi.reset_index()
print(dfi['index'].tolist()) # there could be more than 1 row with the identifier
编辑以将我们在评论中讨论的所有内容放在一起:
file_list = ['C:/MAIL07072021180029.csv','C:/other_file.csv']
for f in file_list:
with open(f, 'r') as file:
data = csv.reader(file)
found = False
for row in data:
if found: # aka found == True - if any column found the value, break to stop iterating
break
for col in range(1, len(row)): # start at 1 to skip col 0
if row[col] == identifyingnumber: # (identifyingnumber) is a tuple(), you probably don't want that
print(row)
found = True
break # if you don't want to look for more instances of identifyingnumber
if not found: # aka found == False
print('I did not find any row[1] equal to', identifyingnumber)