坚持尝试获取行文件的特定部分并将其存储在字典中 - python

时间:2017-02-13 03:45:36

标签: python file loops dictionary

我是python的初学者(和这个网站)&在过去的几个小时里,我一直在尝试采用文件的特定方面,将文件的2个方面组合成字典格式。 ex)123456:John Doe

这就是我的意思,如果这是示例文件:

student_id,student_birthdate,student_address,student_contact,student_name

123456,06-10-1994,123 BirdWay Drive, (123)123-4567,John Doe

789123,03-02-1995,465 Creek Way,(000)456-7890,Jane Doe

P.S。在上面的行中不应该是空格^^我只将它们放在那里,这样你就可以看到每条线的分类方式。 因此,您可以看到有5个类别,第一行告诉您这些类别的顺序,然后所有后面的行只是每个学生信息的巨大文件。这些只是2行2学生,但文件很多,充满了许多学生。我想做的是带上student_id&学生姓名并将其放入字典中 - 格式为:学生ID:学生姓名。还有\ n字符&我也需要摆脱它们。

这是我到目前为止所做的:

def student_id(filename):
    dictionary={}
    file=open(filename,"r")
    content=filename.readlines()
    for line in content:

我认为我必须使用for循环,但我只是不知道如何,我真的要沮丧地哭泣。任何帮助都非常感谢&因为我是初学者,所以我想要非常简单的代码,所以用最少的pythonic方式,非常感谢你!

3 个答案:

答案 0 :(得分:1)

Python的csv module旨在处理包含逗号分隔值的文件。

import csv

def student_id(filename):
    with open(filename, mode='r', encoding='utf-8') as f:
        reader = csv.DictReader(f, delimiter=',')
        data = list(reader)
    data = {item["student_id"]:item["student_name"] for item in data}

或者(可能是你要求这样做的方式):

def student_id(filename):
    results = {}
    f = open(filename, 'r')
    f.readline() # skip the header
    lines = f.readlines()
    f.close()
    for line in lines:
        item = line.strip().split(",")
        results[item[0]] = item[4]
    return results

这并不是一种正确的Pythonic方式。一旦你了解它,你会做类似的事情:

def student_id(filename):
    with open(filename, 'r') as f:
        items = [item.strip().split(",") for item in f.readlines()[1:]]
        return {item[0]:item[4] for item in items}

或者,如果你感觉特别邪恶:

def student_id(filename):
    with open(filename, 'r') as f:
        return {item[0]:item[4] for item in [item.strip().split(",") for item in f.readlines()[1:]]}

答案 1 :(得分:0)

类似的东西:

with open("student.txt") as f:
    content = f.readlines()
content = [x.strip() for x in content]

这将读取文件的每一行,并将其存储在列表content中。

编辑:如果您只是将f.readlines()的每个元素附加到列表中,您将在列表中的每个元素的末尾获得新行字符\n。这就是为什么上面的代码是一个很好的方法;您不必担心删除\n。如果您想要没有with语句的内容,可以尝试:

f = open("student.txt") # Open the file
List = [] # List to store lines in

for row in f: # Go through each line in the file
    row = row.translate(None, '\n') # Remove \n from the line
    List.append(row) # Add the line to the list

答案 2 :(得分:0)

由于您使用的是csv数据,因此可以使用csv.DictReader来简化文件的解析:

import pprint #for the sake of this demo

import csv
filename = "test.txt" #for the sake of this demo

with open(filename, "r") as f:
    #it will automatically detect the first line as the field names
    for details in csv.DictReader(f):
        pprint.pprint(dict(details)) #for this demo

使用您提供的示例文本输出:

{'student_address': '123 BirdWay Drive',
 'student_birthdate': '06-10-1994',
 'student_contact': ' (123)123-4567',
 'student_id': '123456',
 'student_name': 'John Doe'}
{'student_address': '465 Creek Way',
 'student_birthdate': '03-02-1995',
 'student_contact': '(000)456-7890',
 'student_id': '789123',
 'student_name': 'Jane Doe'}

所以要映射id:name,你只需要这样做:

 id = details["student_id"]
 dictionary[id] = details["student_name"]

代替pprint