create array through a python file

Asked

Viewed 20 times

0

I’m a beginner in python, and I’m trying to create a code to display login information, in a text file the information is saved like this: 13:30, Gabriel Santana, 12345678 in the case what is saved in the file is the time of the login, the user’s name, and its number, however when I try to transform into matrix through this code:

arquivo = open('arquivo.txt', 'r')
linha = {}
linha = arquivo.readline()
print(linha[0])

the intention with the line[0] was to print the time and if it were line[1] print the name, but what is shown is the character of the order defined among the []

  • Please update the post with part of the arquivo.txt

  • on file saved as follows: 13:30, Fabiel Antana, 12345678

1 answer

0

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.

Browser other questions tagged

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