找回密码
 快速注册
搜索
查看: 33|回复: 1

[Python] 文件读取为字典

[复制链接]

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

hbghlyj 发表于 2022-8-3 06:48 |阅读模式
utils.py


我们创建了一个函数 file2dict,放入一个名为“utils”的模块中。
该函数以文件名作为参数,读取文件中的行,该文件每行包含两个词,并返回一个 Python 字典,其中每行的第一个单词是键,第二个单词是对应的值。
1 (2).png
  1. def file2dict(filename):
  2.     dict={}
  3.     data = open(filename)
  4.     for line in data:
  5.         [ key, value ] = line.split()
  6.         dict[key] = value
  7.     data.close()
  8.     return dict
复制代码
1 (2).png

We know how to create a function – chiefly, we need to decide on its name and the name(s) of  its argument(s). This function is called “file2dict()” and its single argument is “filename”.  Remember that the body of the function must be indented.

This function takes the approach to creating a dictionary of starting with an empty one and adding entries as it proceeds. So first it creates an empty dictionary.

It needs access to the content of the file so it opens the file to read it.

Next it needs to step through the lines of the file. It uses the standard Python trick of treating something like a list and having it behave like a list.

Then it needs to split the line into two words. It does this using the split() method (with which you should be familiar). Note that split discards all white space, including the new line character as well as the spaces between the words.  Observe that it assigns the list of words generated to a list of two variable names. If any lines in the file don't consist of exactly two words, this line (and the function) will fail.

Having got two words it adds them into the dictionary.

Once it finishes with the file it closes it.

Now that it is done it hands back the dictionary, and the function ends.

3149

主题

8386

回帖

6万

积分

$\style{scale:11;fill:#eff}꩜$

积分
65391
QQ

显示全部楼层

 楼主| hbghlyj 发表于 2022-8-3 08:50
utils_edited.py
修改过的程序会对输入的文件进行检查, 如果在open()发生异常, 就会抛出IOError(可能是因为文件不存在,或没有读取权限); 如果不是每行两个单词, 就会抛出ValueError
  1. def file2dict(filename):
  2.     """file2dict takes a file name as its argument.
  3. This file must contain pairs of words.
  4. It returns the equivalent Python dictionary."""
  5.     import sys
  6.     dict={}
  7.     data = None
  8.     try:
  9.         data = open(filename)
  10.         for line in data:
  11.             try:
  12.                 [ key, value ] = line.split()
  13.             except ValueError:
  14.                 print "File %s is not in the correct format." % filename
  15.                 dict = None
  16.                 break
  17.             dict[key] = value
  18.         data.close()
  19.     except IOError, error:
  20.         (errno, errdetails) = error
  21.         print "Problem with file %s: %s" % (filename, errdetails)
  22.         print "Aborting!"
  23.         if type(data) == file:
  24.             data.close()
  25.         sys.exit(1)
  26.     return dict
复制代码

手机版|悠闲数学娱乐论坛(第3版)

GMT+8, 2025-3-4 15:38

Powered by Discuz!

× 快速回复 返回顶部 返回列表