我是新手,很抱歉这个愚蠢的问题。
我使用python笔记本的JSON格式。 在一行中,打开文件:
f=open(namefile)
在另一本中,我创建了词典:
fips=dict()
for row in f:
bla bla bla
如果我先运行第一个,然后再运行第二个,一切正常,并且字典创建正确,但是如果我尝试重新运行第二行,则字典将为空。为什么?
答案 0 :(得分:0)
for row in f:
这行代码在文件的每一行中运行一个循环,但它基本上是一个生成器,这意味着它仅运行一次。运行另一个循环将始终失败:
for row in f:
print('in the loop')
# Nothing is printed
正确的方法是首先将所有行保存到另一个变量中:
f=open(namefile)
lines = f.readlines()
然后您可以对其进行多次遍历:
fips=dict()
for row in lines:
print('in first loop')
for row in lines:
print('in second loop')