Search for a sub-string in the first column of a csv file

0

I'm starting to learn in python and I do not know how to proceed with this code.

I need to check the first column of a csv file, and if it does NOT have a date in a cell of that column, insert the one that was passed as a parameter.

import csv
import sys

lendo_arquivo = csv.reader(open(sys.argv[1], 'rb'))
escrevendo_arquivo = csv.writer(open(sys.argv[2], 'wb'))

    for linhas in lendo_arquivo:

    if linhas[0] == "201":
        pass
    else:
        escrevendo_arquivo.writerow([sys.argv[3] + ";"] + linhas)

I came to this point, where it adds the 3rd parameter even though the cell has "201" and still adds a "," (comma) at the end of the cell.

  

201 is the substring of a date, eg 2018

What can I do to bypass the cell that has "201" and remove that comma from the end ???

    
asked by anonymous 20.06.2018 / 19:37

1 answer

2

Assuming your .CSV input file is something like ( entrada.csv ):

2018;ALPHA;3.1415
2018;BETA;1.4142
2007;GAMMA;1.7320
2018;DELTA;2.7182
2007;EPSILON;2.2543

Follow the program on Python able to perform file filtering ( filtro.py ):

import csv
import sys

with open(sys.argv[2], 'w') as csv_saida:
    saida = csv.writer( csv_saida, delimiter=';' )
    with open(sys.argv[1], 'r') as csv_entrada:
        entrada = csv.reader( csv_entrada, delimiter=';' )
        for linha in entrada:
            if not linha[0].startswith("201"):
                saida.writerow( [ sys.argv[3] ] + linha[1:] )

Command line:

python3 filtro.py entrada.csv saida.csv 1970 

Output (% with%):

1970;GAMMA;1.7320
1970;EPSILON;2.2543
    
21.06.2018 / 14:10