mounaim
mounaim

Reputation: 1180

reading data from a file and storing them in a list of lists Python

I have a file data.txt containing following lines :

enter image description here
I would like to extract the lines of this file into a list of lists, each line is a list that will be contained within ListOfLines wich is a list of lists. When there is no data on some cell I just want it to be -1.

I have tried this so far :

from random import randint


ListOfLines=[]

with open("C:\data.txt",'r') as file:
    data = file.readlines()
    for line in data :
        y = line.split()
        ListOfLines.append(y)


with open("C:\output.txt",'a') as output:

    for x in range(0, 120):
        # 'item' represente une ligne
        for item in ListOfLines :
            item[2] = randint(1, 1000)
            for elem in item :
                output.write(str(elem))
                output.write(' ')
             output.write('\n')
output.write('------------------------------------- \n')

How can I improve my program to contain less code and be faster ?

Thank you in advance :)

Upvotes: 0

Views: 1000

Answers (1)

SZIEBERTH Ádám
SZIEBERTH Ádám

Reputation: 4206

Well, sharing your sample data in an image don't make easy to working with it. Like this I don't even bother and I assume others do the same.

However, data = file.readlines() forces the content of the file into a list first, and then you iterate through that list. You could do that instantly with 'for line in file:'. That improves it a little.

You haven't mentioned what you want with the otput part which seems quite messy.

Upvotes: 1

Related Questions