[英]How do I read from a .txt file in Python and take specific things from it and put it in a tuple?
所以我想用Python讀取一個.txt文件,並從文件中獲取特定的字符串,並將它們排列在一個元組中。 到目前為止,我的代碼是:
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)
它顯然還沒有完成,這就是為什么我被卡住了。
首先,您可以使用file_list = opened_file.readlines()而不是for循環。 但是要回答您的問題,您可以使用line.find(“ search key”)如果在行中找到字符串“ search key”,它將返回一個數字> = 0。 如果不在行中,它將返回-1。 https://www.tutorialspoint.com/python/string_find.htm
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.