簡體   English   中英

在 python 中迭代文本文件的更有效方法?

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

我試圖做的是讀取文件並將信息存儲在單獨的列表中。 對於這個程序,一個小的示例文件首先用於確保代碼正常工作,但是這個程序將處理 100,000 的照片,這似乎不是索引文件以獲得最佳效率的最佳方式。 這是我到目前為止所擁有的:

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

    

我可以告訴您索引文件的唯一原因是獲取第一行。

您可以使用next()得到這個,然后繼續循環

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM