将字典写入txt文件并将其读回?

Rad*_*ead 98 python

我正在尝试将字典写入txt文件.然后通过键入键来读取dict值raw_input.我觉得我只是错过了一步,但我一直在寻找一段时间.

我收到这个错误

File "name.py", line 24, in reading
    print whip[name]
TypeError: string indices must be integers, not str
Run Code Online (Sandbox Code Playgroud)

我的代码:

#!/usr/bin/env python
from sys import exit

class Person(object):
    def __init__(self):
        self.name = ""
        self.address = ""
        self.phone = ""
        self.age = ""
        self.whip = {}

    def writing(self):
        self.whip[p.name] = p.age, p.address, p.phone
        target = open('deed.txt', 'a')
        target.write(str(self.whip))
        print self.whip

    def reading(self):
        self.whip = open('deed.txt', 'r').read()
        name = raw_input("> ")
        if name in self.whip:
            print self.whip[name]

p = Person()

while True:
    print "Type:\n\t*read to read data base\n\t*write to write to data base\n\t*exit to exit"
    action = raw_input("\n> ")
    if "write" in action:
        p.name = raw_input("Name?\n> ")
        p.phone = raw_input("Phone Number?\n> ")
        p.age = raw_input("Age?\n> ")
        p.address = raw_input("Address?\n>")
        p.writing()
    elif "read" in action:
        p.reading()
    elif "exit" in action:
        exit(0)
Run Code Online (Sandbox Code Playgroud)

KFL*_*KFL 164

你试过json模块吗?JSON格式与python字典非常相似.它是人类可读/可写的:

>>> import json
>>> d = {"one":1, "two":2}
>>> json.dump(d, open("text.txt",'w'))
Run Code Online (Sandbox Code Playgroud)

此代码转储到文本文件

$ cat text.txt 
{"two": 2, "one": 1}
Run Code Online (Sandbox Code Playgroud)

您也可以从JSON文件加载:

>>> d2 = json.load(open("text.txt"))
>>> print d2
{u'two': 2, u'one': 1}
Run Code Online (Sandbox Code Playgroud)

  • 你应该在`with`语句中打开文件进行读/写以确保它在之后关闭? (5认同)
  • 请注意,python 的 json 在执行 json.dump 时会将 dict 键转换为 **strings**,因此 `json.dump({1: 'one'}, file)` 将读回为 `{'1': 'one'} ` 当执行 json.load 时。如果您不打算使用 Python 以外的其他语言读取保存的文件,最好使用 pickle。 (4认同)
  • 哇,真漂亮。 (2认同)
  • 我在一些具有嵌套设置值的复杂字典上使用此方法时遇到了问题(例如`d = {“ one”:{“ 1”:1,“ a”:{“ i”}}}`)。因此,我建议在我的情况下可以使用@blender的pickle方法。 (2认同)

ste*_*eha 82

你的代码几乎正确的!你是对的,你只是错过了一步.当你读入文件时,你正在读它作为一个字符串; 但是你想把字符串变回字典.

您看到的错误消息是因为self.whip是字符串,而不是字典.

我首先写道,你可以只输入字符串,dict()但这不起作用!你需要做点别的事.

这是最简单的方法:将字符串输入eval().像这样:

def reading(self):
    s = open('deed.txt', 'r').read()
    self.whip = eval(s)
Run Code Online (Sandbox Code Playgroud)

你可以在一行中完成它,但我觉得它看起来很麻烦:

def reading(self):
    self.whip = eval(open('deed.txt', 'r').read())
Run Code Online (Sandbox Code Playgroud)

eval()有时候不推荐.问题是eval()会评估任何字符串,如果有人欺骗你运行一个非常棘手的字符串,可能会发生一些不好的事情.在这种情况下,您只是eval()在自己的文件上运行,所以它应该没问题.

但是因为eval()有用,所以有人做了一个更安全的替代品.这是调用的literal_eval,你从一个名为的Python模块中获取它ast.

import ast

def reading(self):
    s = open('deed.txt', 'r').read()
    self.whip = ast.literal_eval(s)
Run Code Online (Sandbox Code Playgroud)

ast.literal_eval() 只会评估变成基本Python类型的字符串,所以没有办法让棘手的字符串在你的计算机上做坏事.

编辑

实际上,Python中的最佳实践是使用with语句来确保文件正确关闭.重写以上内容使用with声明:

import ast

def reading(self):
    with open('deed.txt', 'r') as f:
        s = f.read()
        self.whip = ast.literal_eval(s)
Run Code Online (Sandbox Code Playgroud)

在最流行的Python中,称为"CPython",您通常不需要该with语句,因为内置的"垃圾收集"功能将证明您已完成该文件并将为您关闭它.但是其他Python实现,如"Jython"(Java VM的Python)或"PyPy"(一个非常酷的实验系统,具有即时代码优化)可能无法为您关闭文件.养成使用习惯很好with,我认为它使代码很容易理解.


Ble*_*der 65

要将Python对象存储在文件中,请使用以下pickle模块:

import pickle

a = {
  'a': 1,
  'b': 2
}

with open('file.txt', 'wb') as handle:
  pickle.dump(a, handle)

with open('file.txt', 'rb') as handle:
  b = pickle.loads(handle.read())

print a == b # True
Run Code Online (Sandbox Code Playgroud)

请注意,我从未设置过b = a,而是腌制a到一个文件然后将其打开b.

至于你的错误:

self.whip = open('deed.txt', 'r').read()
Run Code Online (Sandbox Code Playgroud)

self.whip是一个字典对象.deed.txt包含文本,因此当您加载deed.txtinto 的内容时self.whip,self.whip将成为其自身的字符串表示形式.

您可能希望将字符串计算回Python对象:

self.whip = eval(open('deed.txt', 'r').read())
Run Code Online (Sandbox Code Playgroud)

请注意eval听起来如何evil.那是故意的.请改用pickle模块.

  • _要将Python对象存储在文件中,请使用pickle module_除非这些是配置文件,因此您希望它们可以被人类编辑 - 请参阅[为什么要使用python和配置文件?](http://www.robg3d.com/?p = 1000) (2认同)
  • 完美的。这正是我所需要的:将本机 python 结构状态存储在用户不可编辑的文件中。 (2认同)

Pas*_*ten 8

我创建了自己的功能,非常好用:

def writeDict(dict, filename, sep):
    with open(filename, "a") as f:
        for i in dict.keys():            
            f.write(i + " " + sep.join([str(x) for x in dict[i]]) + "\n")
Run Code Online (Sandbox Code Playgroud)

它将首先存储键名,然后存储所有值.请注意,在这种情况下,我的dict包含整数,这就是它转换为的原因int.这很可能是您需要根据自己的情况进行更改的部分.

def readDict(filename, sep):
    with open(filename, "r") as f:
        dict = {}
        for line in f:
            values = line.split(sep)
            dict[values[0]] = {int(x) for x in values[1:len(values)]}
        return(dict)
Run Code Online (Sandbox Code Playgroud)


Man*_*uli 8

嗨,有一种方法可以将字典写入和读取到文件,您可以将字典转换为 JSON 格式并快速读取和写入,只需执行以下操作:

为了你的约会:

 import json

 your_dictionary = {"some_date" : "date"}
 f = open('destFile.txt', 'w+')
 f.write(json.dumps(your_dictionary))
Run Code Online (Sandbox Code Playgroud)

读取您的数据:

 import json

 f = open('destFile.txt', 'r')
 your_dictionary = json.loads(f.read())
Run Code Online (Sandbox Code Playgroud)


Ara*_*mar 5

您可以遍历键值对并将其写入文件

pair = {'name': name,'location': location}
with open('F:\\twitter.json', 'a') as f:
     f.writelines('{}:{}'.format(k,v) for k, v in pair.items())
     f.write('\n')
Run Code Online (Sandbox Code Playgroud)