如何阅读和操作字典和文件python 2.7 [重复]

时间:2021-03-05 18:20:24

This question already has an answer here:

这个问题在这里已有答案:

i have a file that looks like so: {"Apples": 14, "Bananas": 14, "Pineapples": 0, "Pears": 8}

我有一个看起来像这样的文件:{“苹果”:14,“香蕉”:14,“菠萝”:0,“梨子”:8}

im trying to figure out how i can read this file in and be able to use it so that i can for example reduce the "apples" value to lower i.e 13 from 14

即时通讯试图找出我如何阅读此文件并能够使用它,以便我可以例如将“苹果”值降低到更低,即14从14

1 个解决方案

#1


0  

Assuming its just a text file:

假设它只是一个文本文件:

You can just read the file and create a dictionary using literal_eval()

您可以使用literal_eval()读取文件并创建字典

from ast import literal_eval
with open("file.txt") as f:
    a = f.read()
    dic= literal_eval(a)

At this point you can just modify anything in the dict:

此时你可以修改dict中的任何内容:

dic["apples"] = 13

To write it back to file you can just convert it back to a string and write:

要将其写回文件,您只需将其转换回字符串并写入:

w = str(dic)

with open("file.txt", "w+") as f:
    f.write(w)

#1


0  

Assuming its just a text file:

假设它只是一个文本文件:

You can just read the file and create a dictionary using literal_eval()

您可以使用literal_eval()读取文件并创建字典

from ast import literal_eval
with open("file.txt") as f:
    a = f.read()
    dic= literal_eval(a)

At this point you can just modify anything in the dict:

此时你可以修改dict中的任何内容:

dic["apples"] = 13

To write it back to file you can just convert it back to a string and write:

要将其写回文件,您只需将其转换回字符串并写入:

w = str(dic)

with open("file.txt", "w+") as f:
    f.write(w)