I'm trying to create a simple parser for CSV files. I'm trying to use the easiest way to look through the parser to look for a value(row).
import csv
"""
with open('C:/MAIL07072021180029.csv', 'r') as file:
proxy = csv.reader(file)
for row in proxy:
print(row[0])
"""
identifyingnumber = input("What is the number? ")
with open('C:/MAIL07072021180029.csv', 'r') as file:
data = csv.reader(file)
for row in data:
if row[1] == (identifyingnumber):
print(row)
After I run the code and I enter the proxy number(identifying number, the data in my excel). The program just stops? It's not printing the row.
Here is a sample data from my csv file:
Card Identifying Sequence
1873356
I printed out row 0 by taking out if, the row was printed successful, the identifying number.
Is this some kind logic error? I cannot figure this out.
Your csv file may not have the identifying number in it, in which case nothing will print out, because of your 'if' statement. You could check for whether you ever found the number, and if so, break (if you don't want to check other rows for yet another instance of the number), and if not, print that you never found the number.
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)
I highly recommend Pandas for what you are trying to do. Open the csv in Pandas and then check all rows at once for the value, instead of iterating through rows. 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
Edit to put everything together from our discussion in the comments:
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)