将dict写入txt文件并读取回来? [英] Writing a dict to txt file and reading it back?

查看:87
本文介绍了将dict写入txt文件并读取回来?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to write a dictionary to a txt file. Then read the dict values by typing the keys with raw_input. I feel like I am just missing one step but I have been looking for a while now.

我收到此错误

File "name.py", line 24, in reading
    print whip[name]
TypeError: string indices must be integers, not str

我的代码:

#!/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)

推荐答案

您的代码几乎是正确的!你是对的,你只是少了一步.当您读入文件时,您将其作为字符串读取;但你想把字符串变回字典.

Your code is almost right! You are right, you are just missing one step. When you read in the file, you are reading it as a string; but you want to turn the string back into a dictionary.

您看到的错误消息是因为 self.whip 是一个字符串,而不是字典.所以你需要把字符串转换成字典.

The error message you saw was because self.whip was a string, not a dictionary. So you need to convert the string to a dictionary.

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

Here is the simplest way: feed the string into eval(). Like so:

def reading(self):
    s = open('deed.txt', 'r').read()
    self.whip = eval(s)

你可以在一行中完成,但我认为这样看起来很乱:

You can do it in one line, but I think it looks messy this way:

def reading(self):
    self.whip = eval(open('deed.txt', 'r').read())

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

But eval() is sometimes not recommended. The problem is that eval() will evaluate any string, and if someone tricked you into running a really tricky string, something bad might happen. In this case, you are just running eval() on your own file, so it should be okay.

但是因为 eval() 很有用,所以有人提出了一个更安全的替代方案.这称为 literal_eval,您可以从名为 ast 的 Python 模块中获取它.

But because eval() is useful, someone made an alternative to it that is safer. This is called literal_eval and you get it from a Python module called ast.

import ast

def reading(self):
    s = open('deed.txt', 'r').read()
    self.whip = ast.literal_eval(s)

ast.literal_eval() 只会评估转换为基本 Python 类型的字符串,因此棘手的字符串不可能在您的计算机上做坏事.

ast.literal_eval() will only evaluate strings that turn into the basic Python types, so there is no way that a tricky string can do something bad on your computer.

实际上,Python 中的最佳实践是使用 with 语句来确保文件被正确关闭.重写上面的代码以使用 with 语句:

Actually, best practice in Python is to use a with statement to make sure the file gets properly closed. Rewriting the above to use a with statement:

import ast

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

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

In the most popular Python, known as "CPython", you usually don't need the with statement as the built-in "garbage collection" features will figure out that you are done with the file and will close it for you. But other Python implementations, like "Jython" (Python for the Java VM) or "PyPy" (a really cool experimental system with just-in-time code optimization) might not figure out to close the file for you. It's good to get in the habit of using with, and I think it makes the code pretty easy to understand.

这篇关于将dict写入txt文件并读取回来?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆