读取文本文件并在python中形成字典 [英] Read a text file and form a dictionary in python

查看:320
本文介绍了读取文本文件并在python中形成字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有data.txt文件,在python代码下面读取文本并形成字典.

I have file data.txt , below python code reads a text and forms dictionary.

文件:data.txt

file: data.txt

10/20   vinay   
05/31   hunachyal
11/23   mine

bday_list = {}


infile = open("data.txt")
for line in infile:
    List_array = [w.strip() for w in line.split("\t")]
    bday_list[List_array[0]] = List_array[1]
#    print line

print bday_list


 Op: {'11/23': 'mine', '10/20': 'vinay', '05/31': 'hunachyal'}

类似地,如何以OP中所示的格式获取以下文件的判别力

Similarly how to get dictinaory for the below file in the format as shown in OP

文件

  10/20 Name    vinay   phone   +91094xxx   
  05/31 Name    hunachyal   phone +91jndjxx
  11/23 Name    mine    phone +92jdddxxx

  OP:

  {'11/23': {'Phone': '+91kexxx', 'Name': 'mine'}, '10/20': {'Phone': '+919xxxx', 'Name': 'vinay'}, '05/31': {'Phone': '+9194xxxx', 'Name': 'hunachyal'}}

或者python中是否有任何方法可以形成数据库,以便我可以轻松获取数据.

Or Is there any method in python to form data base where i can easily fetch data .

推荐答案

您也可以尝试

bday_list = {}
with open('data.txt', 'r') as R:
    for line in R:
        l = line.strip().split()  # split the line to list
        bday_list[l[0]] = {k:v for k,v in zip(l[1::2], l[2::2])}


PS,
如果您使用的是infile = open(...)而不是with open() as infile:来处理文件句柄,则应该记住之后要close文件句柄.


PS,
If you are using infile = open(...) and not with open() as infile: to work with a file handle, you should remember to close the file handle afterward.

这篇关于读取文本文件并在python中形成字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆