小编Noo*_*123的帖子

换行:不返回所有行

我试图遍历一个文本文件,并采取每一行,并将其放入字典.例如:如果txt文件是b c

我正在尝试创建一个字典

word_dict = {'a':1,'b:2','c':3}

当我使用这段代码时:

def word_dict():
fin = open('words2.txt','r')
dict_words = dict()
i = 1
for line in fin:
    txt = fin.readline().strip()
    dict_words.update({txt: i})
    i += 1
print(dict_words)
Run Code Online (Sandbox Code Playgroud)

我的词典只包含部分列表.如果我使用此代码(不尝试构建字典,只需测试):

def word_dict():
fin = open('words2.txt','r')
i = 1
while fin.readline():
    txt = fin.readline().strip()
    print(i,'.',txt)
    i += 1
Run Code Online (Sandbox Code Playgroud)

一样.它会打印一个不完整的值列表.该列表与字典值匹配.我错过了什么?

python dictionary readlines

4
推荐指数
1
解决办法
60
查看次数

标签 统计

dictionary ×1

python ×1

readlines ×1