Find a sub-string in the first column of a csv file

Asked

Viewed 237 times

0

I am starting learning in python and do not know how to continue this code.

I need to check the first column of a csv file, and if I don’t have a date in a cell in that column, insert the one that was passed as 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 arrived at this point, where he adds the 3° parameter even if the cell has "201" and still adds a "," (comma) at the end of the cell.

201 is the substring of a date, ex: 2018

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

  • Post some lines of the file. Some that have the 201 and others that do not.

1 answer

2


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

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

Follows the program in 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 

Exit (saida.csv):

1970;GAMMA;1.7320
1970;EPSILON;2.2543

Browser other questions tagged

You are not signed in. Login or sign up in order to post.