Doubt with print and with for

Asked

Viewed 49 times

2

for l in arquivo:
   Print(l)

In this file are the name information, IP and Hostname. I need to print the name, IP and Hostname, however in this format:

Name space of 10 characters Ip space of 10 characters Hostname

How do I do it?

  • Have you ever thought about separating the data with semicolons, thus generating a csv? Reading is much easier

1 answer

1

I made a code from what I understood of your question and it got like this:

# Faço a importação da biblioteca que manipula CSV.
import csv

# Abre o arquivo 'arquivocsv.csv' no mesmo diretório './' com o objetivo de ler 'r'.
arquivo = open(r'./arquivocsv.csv', 'r')

# Cria uma função e recebe o parâmetro para formatação, parâmetro esse que seria o arquivo lido
def formatar(arquivo):
    # Cria um laço de repetição para lada elemento dentro do arquivo lido.
    for l in csv.reader(arquivo, delimiter=','):
        # Utilizo um recurso onde posso substituir os {} por uma variável, seleciono posição por posição.
        # Printo cada linha com a formatação correta.
        print('{}          {}          {}'.format(l[0], l[1], l[2]))

# Executo a função
formatar(arquivo)

within the file 'arquivocsv.csv' I have the following text:

Joao,192.168.1.1,joao.exemple.com
  • 1

    Okay, I’ll do that next few times. Thanks for the suggestion.

  • 1

    if you want you can tabulate the print formatted with return(f'{l[0]}\t\t\t{l[1]}\t\t\t{l[2]}')

  • 1

    yes, but I still prefer to use the substitution in the string, in my view it is cleaner. but it is also an option.

  • It did not work, the error you are giving is the following: "Indexerror: list index out of range", I forgot to mention that it is a . csv

  • It was important information, I updated the code with the real situation. test again, but first log in to your CSV file and see if it is being separated by a comma because your file may be separated by another element such as semicolon and so it will be necessary to modify the delimiter parameter in the loop. but if separated by comma just run the code by changing the file path.

  • Thanks a lot man

Show 1 more comment

Browser other questions tagged

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