【问题标题】:Python file for loop用于循环的 Python 文件
【发布时间】:2021-01-19 10:06:34
【问题描述】:

我是 python 新手,请原谅我的愚蠢。我正在尝试遍历文件(.txt)中的字典。但是,我只想遍历字典中的键,而不是值。我已经尝试了几个小时,但没有取得任何进展。感谢您的帮助。

kluizen = {
    11;kaasstengel,
    1;geheim,
    5;kluisvanpietje,
    12;z@terd@g
 } #the number of a locker with the password afterwards.

f = open('fa_kluizen.txt', 'r') 
contents = f.read() 
print(contents) 

for numbers in contents: print(numbers) 
f.close()

【问题讨论】:

  • for key in dictionary: 如果你遍历字典,你会得到键。
  • 分享你的尝试(代码)和你的文件样本
  • 在添加更多信息时编辑您的帖子,而不是在评论中并解释什么是什么
  • 您应该在字典中使用冒号而不是分号。您要导入的文本文件是否有分号?

标签: python dictionary for-loop key text-files


【解决方案1】:

试试这个:

import json

with open("path/to/file.txt", "r") as f:
    # read the file as dictionary
    file_as_dict = json.load(f) 

    # iterate over the keys
    for key in file_as_dict:
        print(key)

【讨论】:

    【解决方案2】:

    该文件不包含字典,因为您不能将 Python 字典逐字存储在文件中。

    但我同意你的观点,它看起来像一本字典,因为它包含以键值对组织的信息。

    你有兴趣从那里取出钥匙:那是储物柜的号码。

    mykeys = []
    
    with open('fa_kluizen.txt', 'r') as fp:
        for line in fp:
            if ';' in line:
                key, value = line.strip().split(';')
    
                mykeys.append(key)
    
    
    # now we have it in mykeys list
    
    for key in mykeys:
        print(key)
    
    

    请试试这个:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-10-31
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-06
      相关资源
      最近更新 更多