Devjyot Kainda
Devjyot Kainda

Reputation: 1

More efficient way of iterating over a text-file in python?

What I have attempted to do is read the file and store the information in separate lists. For this program a small example file is used to first ensure the code works but this program will deal with photos in the 100,000's and this doesn't seem like the best way to index the file for optimal efficiency. This is what I have so far:

with open('a_example.txt') as example_file:    
    content = [i.strip() for i in example_file.readlines()]
    
    number_of_photos = content[0]
    del content[0] #remove the numphoto info
    for j in content:
        orientation_of_photo.append(j[0])
        number_of_tags.append(j[2])

    

Upvotes: 0

Views: 193

Answers (1)

OneCricketeer
OneCricketeer

Reputation: 191844

The only reason I can tell you are indexing the file is to get the first line.

You can use next() to get this, then continue on with the loop

with open('a_example.txt') as example_file:    
    number_of_photos = next(example_file).strip()
    for line in example_file:
        j = line.strip()
        orientation_of_photo.append(j[0])
        number_of_tags.append(j[2])

Upvotes: 2

Related Questions