在 Python 中将文件读入字典 [英] Read files into a dictionary in Python

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

问题描述

当我试图将这些读入字典时,我做错了什么?

尝试将值读入字典时出现此错误:

I am getting this error when trying to read values into a dictionary:

Traceback (most recent call last):
  File "<pyshell#27>", line 1, in <module>
    ListAllFiles()
  File "C:\Python27\1.py", line 14, in ListAllFiles
    (key, val) = line.split('=')
ValueError: need more than 1 value to unpack

我正在使用此代码打开目录中的每个文本文件并将其内容读入字典:

I am using this code to open every text file in the directory and read its contents into a dictionary:

from __future__ import print_function
import glob
import os

# Let's read all the files into the set
def ListAllFiles():
    mydir="C:\\Python27"
    os.chdir(mydir)
    for file in glob.glob("*.txt"):
        #print(mydir+'\\'+file)
        d = {}
        with open(mydir+'\\'+file) as f:
            for line in f:
               (key, val) = line.split('=')
               d[file] = (key,val)
               print (val)

其中一个文本文件的示例是:

an example of one of the text files is:

paramA=Y
paramB=30
paramC=normal
paramD=SOME_ITEM_IN_ALL_CAPS
paramE=5 6 7 8 9 
paramF=/dir/to/stuff
paramG=y

我希望字典看起来像这样:

I would like the dictionary to look like this:

+-----------+--------+-----------------------+
| filename1 | paramA | Y                     |
| filename1 | paramB | 30                    |
| filename1 | paramC | normal                |
| filename1 | paramD | SOME_ITEM_IN_ALL_CAPS |
| filename1 | paramE | 5 6 7 8 9             |
| filename1 | paramF | /dir/to/stuff         |
| filename1 | paramG | y                     |
| Filename2 | paramA | A                     |
| Filename2 | paramB | 22                    |
| Filename2 | paramC | st                    |
| Filename2 | paramD | AAAA                  |
| Filename2 | paramE | 5 6 7 8 9             |
| Filename2 | paramF | ff                    |
| Filename2 | paramG | g                     |
| Filename3 | etc    | etc                   |
+-----------+--------+-----------------------+

我想字典应该是这样的:

I would imagine the dictionary would be something like this:

d={filename1:(ParamA='A', ParamB='22', Paramc='st'....),filename2:(paramA=...

当我试图将这些读入字典时,我做错了什么?

推荐答案

您很可能在其中一个文件中有空行.

You most probably have an empty line in one of the files.

使用 if 行:try...except

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

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