简体   繁体   中英

How do I read from a .txt file in Python and take specific things from it and put it in a tuple?

So I want to read a .txt file in Python and take specific strings from the file and arrange them in a tuple. My code so far is:

opened_file = open(name_of_file, 'r')
file_list = []
candidate_dictionary = {'Donald Trump':'1st', 'Hillary Clinton':'2nd'}
for line in opened_file:
    file_list.append(line)

It obviously isn't complete yet, and that is why i'm stuck.

Well first you could use file_list=opened_file.readlines() rather than a for loop. But to answer your question you could use line.find("search key") this will return a number >=0 if the string "search key" is found in the line. If it is not in the line it will return a -1. https://www.tutorialspoint.com/python/string_find.htm

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