Use the module csv
. With it you can define the column separator and even read each row as a dictionary, making it easy to read the code.
import csv
def get_address_from_file(filename):
with open(filename, 'r') as stream:
reader = csv.DictReader(stream, delimiter=';')
for row in reader:
yield row['Endereço']
So, if you have a file like, for example:
Nome;Email;Telefone;Endereço;ECivil
Foo;[email protected];0;Brasilia;Solteiro
Bar;[email protected];0;Curitiba;Casado
Just do:
for endereco in get_address_from_file('arquivo.txt'):
print(endereco)
The exit would be:
Brasilia
Curitiba
See working on Repl.it
You can still generalize the function by passing the column name by parameter, if you need to access other columns at other times:
def get_column_from_file(filename, column):
with open(filename, 'r') as stream:
reader = csv.DictReader(stream, delimiter=';')
for row in reader:
yield row[column]
And make:
for endereco in get_column_from_file('arquivo.txt', 'Endereço'):
print(endereco)
Thank you Anderson, you saved my life rsrs
– user68537
And face only one doubt there is another way? For there is another script that reads all the lines and makes another process =/
– user68537
@Wallacebrunogentil yes, there are several forms, depends on what you need to do. The way I put it, how it uses the
yield
in the function, the return will be a generator, making the file does not need to stay whole in memory. You can read files of a few megas or gigas that will work without problem. It just depends on what your needs are.– Woss
But then, how can I do without there being a 1 line with the dictionary?
– user68537
I don’t know what you mean.
– Woss
In this case, the file I have, already begins with the data, there is a data header stating what each field symbolizes, I understood the use of CSV but I do not see how to use this feature without having a the header understands?
– user68537
Got it. You can use
csv.reader
instead ofcsv.DictReader
, so the return will be a list instead of a dictionary, you can access the address withrow[3]
.– Woss
I just saw that in the documentation it shows the Reader and the Dictreader, sorry for the faltering... lack of attention, thank you very much for having shown me the CVS rsrs will help me a lot!
– user68537