[英]Reading a text file then storing first and third word as key and value respectively in a dictionary
這是代碼:
def predator_eat(file):
predator_prey = {}
file.read()
for line in file:
list = file.readline(line)
list = list.split(" ")
predator_prey[list[0]] = list[2]
print(predator_prey)
predator_eat(file)
文本文件每行三個單詞,每行末尾帶有\\ n,我以前打開了文件,並使用file = open(filename.txt,r)將文件名存儲為變量文件
print語句最終是一個空字典,因此不會在字典中添加鍵和值
請幫忙
您對.read()
第一次調用會消耗整個文件的內容,而循環則不會進行任何操作。 去掉它。 該.readline()
調用沒有任何用處。 也將其刪除。
這應該工作:
def predator_eat(file):
predator_prey = {}
for line in file:
words = line.split(" ")
predator_prey[words[0]] = words[2]
print(predator_prey)
整理一下代碼:
def predator_eat(f):
predator_prey = {}
for line in f:
rec = line.strip().split(" ")
predator_prey[rec[0]] = rec[2]
return predator_prey
with open(path) as f:
print predator_eat(f)
您基本上是在聲明python關鍵字,將文件更改為fileToRead並列出諸如totalList之類的其他內容。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.