Some questions with your code.
arquivo = open('arquivo.txt', 'r') # 1
linha = {} # 2
linha = arquivo.readline() # 3
print(linha[0]) # 4
Note #1
This line is OK
Note #2
This line has no reason to be here, because immediately below, you reset the variable linha
Note #3
This command reads only one line, so it should be within a loop.
Note #4
linha
is a variable of the type str
(String), so the index 0 (zero) is the first character of the string.
Alternatives
Use the readlines()
arquivo = open('arquivo.txt', 'r')
linhas = arquivo.readlines()
arquivo.close() # 5
for linha in linhas:
campos = linha.replace("\n", "").split(",") # 6
print(campos[0], campos[1], campos[2])
Use readline() inside a repeat loop
arquivo = open('arquivo.txt', 'r')
linha = arquivo.readline()
while linha:
linha = linha.replace("\n", "")
campos = linha.split(",")
print(campos[0], campos[1], campos[2])
linha = arquivo.readline()
arquivo.close()
Note #5
Using this form, don’t forget to close the file
Note #6
You have to do the replace("\n","")
to replace line breaks with empty and use the split(",")
to separate the string into items from a list
Most correct way to read a file
with open('arquivo.txt', 'r') as arquivo:
# processa o arquivo aqui.
So, Python itself is in charge of closing the file, if you have a problem "halfway"
Another way would be:
linhas = open('arquivo.txt', 'r').readlines()
Being a file with lines separated by comma, ie a CSV file. I suggest to read about the library csv
python here.
Please update the post with part of the
arquivo.txt
– Paulo Marques
on file saved as follows: 13:30, Fabiel Antana, 12345678
– Gabriel Santana