简体   繁体   中英

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

    

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM