Você nem precisaria usar csv.reader()
para fazer isso. Aqui está um exemplo (trabalhando em python 3.6) como fazê-lo sem, apenas usando as funções internas do python e a biblioteca sys
para analisar a linha de comando. Então, aqui está um exemplo sem a biblioteca csv
, vamos chamá-lo de search_basic.py
:
#!/usr/bin/env python3.6
from sys import argv
def parse_files(name_1, name_2):
"""Opens two files and checks if pos #6 in each row of file 1 is present in file2 via simple build-ins"""
try:
with open(file=name_1) as file_1, open(file=name_2) as file_2:
data_1 = file_1.readlines()
data_2 = file_2.readlines()
mapping = {
row.strip('\n').split('|')[-1]: row.strip('\n').split('|')
for row in data_2
}
for row in data_1:
last_column = row.strip('\n').split('|')[-1]
if last_column in mapping:
print(f'{last_column} found in {mapping[last_column]}')
else:
print(f'{last_column} not found, doing other operation')
except FileNotFoundError as error:
print('{}'.format(error))
exit(1)
else:
return
if __name__ == "__main__":
if len(argv) <= 1:
print('No parameters given...')
exit(1)
elif len(argv) == 2:
print('Only one file was given...')
exit(1)
else:
parse_files(argv[1], argv[2])
exit(0)
Mas se você insistir em usar a biblioteca csv
, veja o exemplo (trabalhando em python 3.6) fazendo isso com csv.reader()
, vamos chamá-lo de search_csv.py
:
#!/usr/bin/env python3.6
import csv
from sys import argv
def parse_files(name_1, name_2):
"""Opens two files and checks if pos #6 in each row of file 1 is present in file2 via simple build-ins"""
try:
with open(file=name_1) as file_1, open(file=name_2) as file_2:
mapping = {
row[-1]: row
for row in csv.reader(file_2, delimiter='|')
}
for row in csv.reader(file_1, delimiter='|'):
last_column = row[-1]
if last_column in mapping:
print(f'{last_column} found in {mapping[last_column]}')
else:
print(f'{last_column} not found, doing other operation')
except FileNotFoundError as error:
print('{}'.format(error))
exit(1)
else:
return
if __name__ == "__main__":
if len(argv) <= 1:
print('No parameters given...')
exit(1)
elif len(argv) == 2:
print('Only one file was given...')
exit(1)
else:
parse_files(argv[1], argv[2])
exit(0)
É claro que você precisa chmodar os dois arquivos para permitir a execução:
chmod 755 search_basic.py
chmod 755 search_csv.py
Dados seusfile1
e file2
acima, ambos produzem a mesma saída com a linha ./search_basic.py file1 file2
(ou respectivo ./search_csv.py file1 file2
):
25353gb1FAa8 found in ['367536', '163226', '163226', '5007632889', '9', '163226', '2017-11-15 20:37:02.034', '2017-11-28 20:55:24.891', 'STB', '25353gb1FAa8', '25353gb1FAa8']
255411429E02 not found, doing other operation
375g1043DC92 found in ['274451', '24575', '24575', '3872531727', '23', '24575', '2017-11-08 11:43:21.15', '2017-11-25 16:30:21.061', 'STB', '375g1043DC92', '375g1043DC92']
07k9975cad1e not found, doing other operation