代码示例:假设文件内容为如下,需要按照title -> author -> text的顺序读取。
title: A Brief History of Time author: Stephen Hawking text: In this widely popular book, Hawking explores the complex topic of space, time and the universe.
title: To Kill a Mockingbird author: Harper Lee text: Set in the deep south during the 1930s, Harper Lee's Pulitzer Prize-winning novel follows the journey of a young girl as she navigates racial injustice and prejudice.
title: The Great Gatsby author: F. Scott Fitzgerald text: A timeless classic about a young, mysterious millionaire Jay Gatsby and his quest for love and wealth in the roaring twenties.
with open("books.txt", "r") as file: data = file.readlines()
books = []
book = {}
for line in data:
# check if starting a new book
if line.startswith('title:'):
book = {}
book['title'] = line.strip('title: ').strip('\n')
elif line.startswith('author:'):
book['author'] = line.strip('author: ').strip('\n')
elif line.startswith('text:'):
book['text'] = line.strip('text: ').strip('\n')
books.append(book)
# read books in specific order
for book in books:
print(book['title'])
print(book['author'])
print(book['text'])
上一篇:按特定顺序从S3复制列数据
下一篇:按特定顺序迭代列表项