简体   繁体   中英

Reading a text file then storing first and third word as key and value respectively in a dictionary

Here's the code:

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)

The text file is three words per line with \\n at the end of each line and I previously opened the file and stored the file name as the variable file using file = open(filename.txt, r)

the print statement ends up being an empty dictionary so it isn't adding keys and values to the dictionary

please help

Your first call to .read() consumes the entire file contents, leaving nothing for the loop to iterate over. Remove it. And that .readline() call does nothing useful. Remove that too.

This should work:

def predator_eat(file):
    predator_prey = {}
    for line in file:
        words = line.split(" ")
        predator_prey[words[0]] = words[2]
    print(predator_prey)

Cleaning up your code a little:

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之类的其他内容。

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