【问题标题】:Can't make dictionary from txt file无法从txt文件制作字典
【发布时间】:2018-08-12 12:45:35
【问题描述】:

所以我在全局范围内定义了一个名为 library 的空白字典。我已经知道如何将字典保存到 txt 文件中。

txt 文件的输出如下所示(称为 bookList0.txt):

{'Hobbit': {'author': 'J.R.R.Tolkien', 'year': '1937', 'genre': 'fantasy'}}

我做了一个函数来加载这个文件:

 library = {}
 def load():
    print("Loading library..")
    f = open("bookList0.txt", "r")
    library = eval(f.readline())
    if len(library) > 0:
        print("Library successfully loaded!")
    else:
        print("Library didn't load!")

如果我使用此功能,它会显示“库已成功加载!”。但是当我在控制台中输入print(library) 时,它只显示{}

但是,如果我在控制台中输入f = open(str("bookList0.txt"), "r") 然后library = eval(f.readline()),然后在控制台中再次输入print(library),它会给我文件中的字典。这样就可以了。

我不知道为什么这在函数中不起作用,但在控制台中起作用。感谢您的帮助!

更新:我尝试使用 json 模块加载,但它仍然没有加载任何内容。这是我为 json 编写的代码:

json_file = open("bookList.json")
json_str = str(json_file.read())
json_data = json.loads(json_str)
library = json_data

问题解决了!这是似乎可以工作的代码:

def load():
    print("Loading library..")
    json_file = open("bookList.json")
    json_str = str(json_file.read())
    json_data = json.loads(json_str)
    library.update(json_data)
    if len(library) > 0:
        print("Library successfully loaded!")
    else:
        print("Library didn't load!")

【问题讨论】:

  • 你不应该使用eval,看看the json module
  • minimal reproducible example,拜托。 (即告诉我们你把你声称产生错误输出的print(library) 放在哪里)
  • @ThierryLathuille 在这种情况下给出了引用 - ast.literal_eval 可能更好......
  • 你应该使用带有loadsdumps函数的JSON模块来处理编码/解码dicts
  • @Barnistic 好的,但是你的load 函数没有返回任何东西,所以print(library) 应该在控制台中抛出一个NameError。除非您之前定义了一个名为 library 的全局变量。所以我重复了我对 MCVE 的要求。

标签: python file dictionary


【解决方案1】:

在我看来,你对 Python 的name scopes 的理解不是很清楚。

我写了一个小脚本,我有(mutatis mutandis,即不涉及外部文件......)两个不同的load定义,load_01,就像在你的代码中一样,没有return 语句和load_02 有一个return 语句,并且我以不同的方式调用这两个函数,即没有或有相应的赋值,并且在这四种情况下,脚本都会打印它的library 的值的想法。

$ cat delendo.py
library = {}
data = '''{
    'Hobbit': 
        {'author': 'J.R.R.Tolkien', 'year': '1937', 'genre': 'fantasy'}}'''

def load_01(s):
    library = eval(s)
    print('Loaded 01')

def load_02(s):
    library = eval(s)
    print('Loaded 02')
    return library

print('='*64)
print('Initial value of _library_')
print(library)

print('='*64)
print('No return, no assignment')
load_01(data) ; print(library)
print('No return, assignment')
library = load_01(data) ; print(library)

print('='*64)
print('Reset value of _library_')
library = {}
print(library)

print('='*64)
print('Return, no assignment')
load_02(data) ; print(library)
print('Return, assignment')
library = load_02(data) ; print(library)

这里有我准备好的脚本的执行结果

$ python delendo.py 
================================================================
Initial value of _library_
{}
================================================================
No return, no assignment
Loaded 01
{}
No return, assignment
Loaded 01
None
================================================================
Reset value of _library_
{}
================================================================
Return, no assignment
Loaded 02
{}
Return, assignment
Loaded 02
{'Hobbit': {'author': 'J.R.R.Tolkien', 'year': '1937', 'genre': 'fantasy'}}
$ 

我希望通过研究代码并面对输出,您可以更好地理解 Python 中的名称范围。


ps,在 cmets 中,所有关于使用 eval 和使用 json 模块的机会都是独立存在的,您应该尝试将收到的建议合并到您的代码中。

我的示例仅针对您面临的问题的一方面,即目前困扰您的问题...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-12
    • 2021-07-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多