Read csv with multiple lines in python

Asked

Viewed 221 times

0

Hello, I would like suggestions on how to read a csv file, I am maintaining a script, but it only returns the first line. I did some tests with some templates I found on the internet again only the first line, pq for each row will be done a check in sql for each contract.

data = csv.reader(open('caminho/contratos.csv', 'r'), delimiter=';')

for linha in data:
    contrato = linha[0]
    cidade = linha[1]

    if contrato == 'CD_CONTRATO':
        logging.info('IDENTIFICOU O CONTRATO: '+contrato)
        continue

    if cidade == 'ID_CIDADE':
        logging.info('IDENTIFICOU A OPERADORA: '+cidade)
        continue

Below the contents in csv file, first contract line, and the second the codcity of the base

1507499;806
2740829;054
612438310;884
612437764;884
15511642;013

thanks in advance for the help.

  • 1

    Show the 5 or 10 first lines of your csv.

  • 1507499;806 2740829;054 612438310;884 612437764;884 15511642;013

  • Edit the question and show the first 5 lines of csv, in the comments do not to do this.

  • I edited the question, added 5 lines with the data in the csv file

  • I did a test with these lines and everything worked normal, your code to read the file and access the lines is ok, I just did not understand your explanation for the 5 lines q vc posted, it is only from a file?

  • is just a file, is that you asked to show 5 or 10 lines of my csv. That’s all.

  • Yes, run a test, create a new file teste.csv with these 5 lines, and open with the same command of the first line of your code in this question, then do: for linha in data: print(linha) and see if you print the 5 lines, if yes, you must have problems with the original file

  • It worked :), I made the change you suggested, thank you very much

  • @Lorenajesus if you can post the answer as solved the problem. Maybe it helps someone who is in the same doubt.

  • Possible duplicate of How to read a CSV file in Python?

Show 5 more comments

1 answer

0

Sidon’s suggestion solved my problem. I created a new file .csv with another name and put for linha in data: print(linha), then it was with problem in the file, now it is checking line by line and doing the checks as expected.

data = csv.reader(open('caminho/teste.csv', 'r'), delimiter=';')

for linha in data:
    print(linha)
    contrato = linha[0]
    cidade = linha[1]

    logging.debug(contrato)


    if contrato == 'CD_CONTRATO':
        logging.info('IDENTIFICOU O CONTRATO: {0}')
        print linha[0]
        continue

    if cidade == 'ID_CIDADE':
        logging.info('IDENTIFICOU A OPERADORA: {1}')
        print linha[1]
        continue

Browser other questions tagged

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