【发布时间】:2016-05-05 18:24:09
【问题描述】:
我正在尝试将以下文本文件放入字典中,但我希望忽略以“#”开头的任何部分或空行。
我的文本文件如下所示:
# This is my header info followed by an empty line
Apples 1 # I want to ignore this comment
Oranges 3 # I want to ignore this comment
#~*~*~*~*~*~*~*Another comment~*~*~*~*~*~*~*~*~*~*
Bananas 5 # I want to ignore this comment too!
我想要的输出是:
myVariables = {'Apples': 1, 'Oranges': 3, 'Bananas': 5}
我的 Python 代码如下:
filename = "myFile.txt"
myVariables = {}
with open(filename) as f:
for line in f:
if line.startswith('#') or not line:
next(f)
key, val = line.split()
myVariables[key] = val
print "key: " + str(key) + " and value: " + str(val)
我得到的错误:
Traceback (most recent call last):
File "C:/Python27/test_1.py", line 11, in <module>
key, val = line.split()
ValueError: need more than 1 value to unpack
我理解错误,但我不明白代码有什么问题。
提前谢谢你!
【问题讨论】:
-
您可以控制文本文件格式吗?如果是这样,也许考虑使用 PyYAML?
-
遗憾的是没有。文本格式是我被指示使用的格式。
-
你检查过答案吗?已经给出了一些好的方法。浏览它们并询问您是否需要更多信息。
-
@Pouria Hadjibagheri:是的,绝对好的方法,谢谢!我们说话的时候我正在经历它们:)
-
我找到了答案。感谢大家非常快速和有用的回复/见解!
标签: python dictionary text comments