0

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 :)

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.