How do I change a line in a data file iterated in Python?

Asked

Viewed 54 times

-2

Oops! I’m trying to create a Python script that reads an external data file, which has several rows and different column numbers. The script I created follows below:`

import numpy as np

entrada = open('dados.dat', 'r')
lista_de_linhas = entrada.readlines()
valor = int(52)
if (lista_de_linhas[72]):
    j=0
    comprimento = len(lista_de_linhas[72])
    print comprimento
    for j in range( 0, (comprimento) ):
        fsaida=open('dados_%i.dat' % (j+1), 'w')
        i = 0
        while i in range( 0, (comprimento) ):
            if (j==i):
                fsaida.write ('%f' % valor)
            else:
                fsaida.write ('%f' % 0)
            break

The script reads the entire input file. I wanted to make a change to line 72 of that file which is a line this way:

inserir a descrição da imagem aqui

I wanted the script to generate, for each output file, a line 72 with a value of 52 and the rest of the values all equal to zero. For example: the output file 1 should have the first value of the column equal to 52 and the rest all null. The second data file should have the second value equal to 52 and the remaining null and so on. But I’m not getting the script to iterate the columns. Can someone help me???

  • 1

    Iae, colleague! The ideal is you [Edit] the question and post your code as text. So you can not reproduce. ;)

  • To start, edit the question and place the code in the body of the text to be able to copy and paste. Another thing: know how this data is saved inside the file dados.dat is essential to help you.

  • Oops! I’ll do it. Thanks!!

  • 1

    Personal altered!

1 answer

0

You can and should use the function iteritems();

Thus:

for x, y in lista_de_linhas.iteritems():

Then just follow your logic.

Python - Iteritems()

  • Hi Rafael. It didn’t work out. This error appears: File "leitor2.py", line 11, in <module> for index, j in lista_de_linhas.itertems(): Attributeerror: 'list' Object has no attribute 'itertems' Why is it? It will be because of the variable indexes?

  • Which version of python are you using? @Flaviorusch

  • Version 2.7.6 Rafael.

  • try list_de_lines.items()

  • Give the same error. A question: at this command line x is the initial index and y is the value to be iterated by the iteritem() function? I researched this function but I didn’t find much.

Browser other questions tagged

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