相关疑难解决方法(0)

在Python中将字典保存到文件(替代pickle)?

回答我最后还是最后去了泡菜

好的,在另一个问题上有一些建议,我问我被告知使用pickle将字典保存到文件中.

我试图保存到文件的字典是

members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'}
Run Code Online (Sandbox Code Playgroud)

当pickle将它保存到文件中时......这就是格式

(dp0
S'Test'
p1
S'Test1'
p2
sS'Test2'
p3
S'Test2'
p4
sS'Starspy'
p5
S'SHSN4N'
p6
s.
Run Code Online (Sandbox Code Playgroud)

你能给我另一种方法将字符串保存到文件中吗?

这是我希望它保存的格式

members = {'Starspy':'SHSN4N','Test':'Test1'}

完整代码:

import sys
import shutil
import os
import pickle

tmp = os.path.isfile("members-tmp.pkl")
if tmp == True:
    os.remove("members-tmp.pkl")
shutil.copyfile("members.pkl", "members-tmp.pkl")

pkl_file = open('members-tmp.pkl', 'rb')
members = pickle.load(pkl_file)
pkl_file.close()

def show_menu():
    os.system("clear")
    print "\n","*" * 12, "MENU", "*" * 12
    print "1. List members"
    print "2. Add member"
    print "3. …
Run Code Online (Sandbox Code Playgroud)

python dictionary save pickle

48
推荐指数
4
解决办法
9万
查看次数

使用Python永久存储字典的优雅方式?

目前昂贵地解析文件,该文件生成约400个键值对的字典,其很少更新.以前有一个解析文件的函数,用字典语法(即.dict = {'Adam': 'Room 430', 'Bob': 'Room 404'})等将它写入文本文件,并将其复制并粘贴到另一个函数中,该函数的唯一目的是返回该解析的字典.

因此,在我将使用该字典的每个文件中,我将导入该函数,并将其分配给变量,现在是该字典.想知道是否有更优雅的方法来做到这一点,这不涉及明确地复制和粘贴代码?使用数据库似乎是不必要的,并且文本文件给了我在将其添加到函数之前查看解析是否正确完成的好处.但我愿意接受建议.

python database json dictionary

19
推荐指数
4
解决办法
3万
查看次数

需要一个类似字节的对象,而不是'str'JSON文件作为STR打开

我只学习了Python的基础知识请原谅我,但我无法确定其他帖子的修复.我用'r'打开我的JSON文件,我想我正在写它们但是它不喜欢它.将其更改为'r'无济于事:(

对于以下部分:

if isinstance(to_write, list):
    self.log_file.write(''.join(to_write) + "<r/>")
else:
    self.log_file.write(str(to_write) + "<r/>")
    self.log_file.flush()
Run Code Online (Sandbox Code Playgroud)

我得到的错误是: a bytes-like object is required, not 'str'

import math
import time
from random import randint
import json

from instagram.client import InstagramAPI

class Bot:
    def __init__(self, config_file, tags_file):
        # Loading the configuration file, it has the access_token, user_id and others configs
        self.config = json.load(config_file)

        # Loading the tags file, it will be keep up to date while the script is running
        self.tags = json.load(tags_file)

        # Log file …
Run Code Online (Sandbox Code Playgroud)

python string byte json

9
推荐指数
1
解决办法
2万
查看次数

将python 3.x字典保存到JSON

这个答案中建议的解决方案允许保存dictjson.例如:

import json
with open('data.json', 'wb') as fp:
    json.dump(data, fp)
Run Code Online (Sandbox Code Playgroud)

但是,这不起作用3.x.我收到以下错误:

TypeError: 'str' does not support the buffer interface
Run Code Online (Sandbox Code Playgroud)

根据这个答案,解决方案是某种演员; 但我无法为字典做这件事.保存dictjson使用python 3.x 的正确方法是什么?

python json dictionary

3
推荐指数
1
解决办法
1889
查看次数

标签 统计

python ×4

dictionary ×3

json ×3

byte ×1

database ×1

pickle ×1

save ×1

string ×1