Reading CSV with Python

Asked

Viewed 444 times

1

As I can go giving a "scan" in the CSV file and when finding certain String in the CSV line, print in another file the complete line with its values after the string. Ex When you find the string "Bruno Lorencini", in csv, print in a second file. "Bruno Lorencini", pageview:1, bounces:2

  • 1

    Possible duplicate of http://answall.com/questions/97269/como-ler-um-arquivo-csv-em-python

1 answer

2

Algorithm:

  • open the input file
  • create the output file
  • for each row of the input file,
    • if the line is equal to the text sought by you,
      • show "I found it!" message to the user
      • write the input file line in the output file

Code:

with open('arquivo_entrada.csv', 'r') as f:
    with open('arquivo_saida.csv', 'w') as g:
        for l in f.readlines():
            if l.strip() == "Bruno lorencini":
                print("Encontrei!")
                g.write(l)
  • 1

    Hi - since Python 3.3 it is possible to open both files with a single "with" block - this way you save a level of indentation, which is very nice for code.

  • And if I want to print the whole line it’s possible ?

Browser other questions tagged

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