source

사전을 파일에 저장하는 방법

itover 2022. 11. 11. 23:31
반응형

사전을 파일에 저장하는 방법

dict 값을 변경하고 dict를 텍스트 파일에 저장하는 데 문제가 있습니다(형식은 같아야 함).member_phone들판.

내 텍스트 파일은 다음 형식입니다.

memberID:member_name:member_email:member_phone

텍스트 파일을 다음과 같이 분할했습니다.

mdict={}
for line in file:
    x=line.split(':')
    a=x[0]
    b=x[1]
    c=x[2]
    d=x[3]
    e=b+':'+c+':'+d

    mdict[a]=e

변경하려고 하면member_phone저장 장소d, 키가 흐르지 않고 값이 변경되었습니다.

def change(mdict,b,c,d,e):
    a=input('ID')
    if a in mdict:
        d= str(input('phone'))
        mdict[a]=b+':'+c+':'+d
    else:
        print('not')

같은 형식의 텍스트 파일에 어떻게 dict를 저장합니까?

Python은 이런 종류의 피클 모듈을 가지고 있습니다.

거의 모든 개체를 저장하고 로드하는 데 필요한 기능은 다음과 같습니다.

with open('saved_dictionary.pkl', 'wb') as f:
    pickle.dump(dictionary, f)
        
with open('saved_dictionary.pkl', 'rb') as f:
    loaded_dict = pickle.load(f)

Python 컬렉션을 저장하기 위해 쉘브 모듈이 있습니다.

피클이 가장 좋은 방법일 것입니다만, NumPy를 사용해 사전을 보존해 파일에 로드하는 방법을 궁금해하는 사람이 있는 경우는, 다음과 같습니다.

import numpy as np

# Save
dictionary = {'hello':'world'}
np.save('my_file.npy', dictionary) 

# Load
read_dictionary = np.load('my_file.npy',allow_pickle='TRUE').item()
print(read_dictionary['hello']) # displays "world"

참고: NPY 파일 뷰어

사전이나 다른 데이터를 JSON 형식으로 쉽게 매핑할 수 있는 경우에도 모듈을 사용할 수 있습니다.

import json

# Serialize data into file:
json.dump( data, open( "file_name.json", 'w' ) )

# Read data from file:
data = json.load( open( "file_name.json" ) )

이 솔루션Python 2.x Python 3.x에서 변경되지 않은 형태로 작동하며 JSON 형식으로 저장된 데이터를 여러 플랫폼 또는 프로그램 간에 쉽게 전송할 수 있는많은 이점제공합니다.이 데이터는 사람이 읽을 수도 있습니다.

파일에 dict 저장 및 로드:

def save_dict_to_file(dic):
    f = open('dict.txt','w')
    f.write(str(dic))
    f.close()

def load_dict_from_file():
    f = open('dict.txt','r')
    data=f.read()
    f.close()
    return eval(data)

첫 번째 질문이 무엇인지 잘 모르겠지만 사전을 파일로 저장하려면json도서관.로드 및 배치 기능의 설명서를 찾습니다.

Peekle은 몇 가지 보안상의 문제가 있고 속도가 느리기 때문에(소스), JSON은 빠르고, 내장되어 있고, 사람이 읽을 수 있고, 호환성이 있기 때문에 저는 JSON을 추천합니다.

import json
data = {'another_dict': {'a': 0, 'b': 1}, 'a_list': [0, 1, 2, 3]}
# e.g. file = './data.json' 
with open(file, 'w') as f: 
    json.dump(data, f)

판독도 마찬가지로 간단합니다.

with open(file, 'r') as f:
    data = json.load(f)

이는 이 답변과 유사하지만 파일 처리를 올바르게 구현합니다.

그래도 성능 향상이 충분하지 않다면 Python용 빠르고 올바른 JSON 라이브러리를 Build on Rust를 적극 추천합니다.

JSON의 파일은 사람이 읽을 수 있기 때문에 데이터가 작기 때문에 디버깅이 용이하기 때문에 피클 형식이 아닌 JSON 형식으로 데이터를 저장하는 것이 좋습니다.JSON 파일은 다른 프로그램에서도 데이터를 읽고 쓰는 데 사용됩니다.자세한 내용은 이쪽에서 확인하실 수 있습니다.

JSON 모듈을 설치해야 합니다.pip을 사용하여 설치할 수 있습니다.

pip install json


# To save the dictionary into a file:
json.dump( data, open( "myfile.json", 'w' ) )

그러면 myfile이라는 이름의 json 파일이 생성됩니다.

# To read data from file:
data = json.load( open( "myfile.json" ) )

그러면 myfile.json 데이터가 데이터 개체에 읽혀 저장됩니다.

당신이 다루고 있는 문자열 사전과 같은 문자열의 경우 파이썬의 내장 텍스트 처리 기능만 사용하여 수행할 수 있습니다.

(값이 다른 것일 경우 이 기능은 작동하지 않습니다.)

with open('members.txt') as file:
    mdict={}
    for line in file:
        a, b, c, d = line.strip().split(':')
        mdict[a] = b + ':' + c + ':' + d

a = input('ID: ')
if a not in mdict:
    print('ID {} not found'.format(a))
else:
    b, c, d = mdict[a].split(':')
    d = input('phone: ')
    mdict[a] = b + ':' + c + ':' + d  # update entry
    with open('members.txt', 'w') as file:  # rewrite file
        for id, values in mdict.items():
            file.write(':'.join([id] + values.split(':')) + '\n')

예쁜 프린트 모듈을 사용하여 사용자가 읽기 쉬운 형태로 딕트를 저장하는 것이 좋습니다.

import pprint

def store_dict(fname, dic):
    with open(fname, "w") as f:
        f.write(pprint.pformat(dic, indent=4, sort_dicts=False))
        # note some of the defaults are: indent=1, sort_dicts=True

후 복구 시 .eval()문자열을 다시 딕트로 변환합니다.

def load_file(fname):
    try:
        with open(fname, "r") as f:
            dic = eval(f.read())
    except:
        dic = {}
    return dic

가장 은 '사전을 가지고 있지 않다', '사전을 가지고 있지 않다'를 합니다.csvPython 모모 。 행이 수 요.member_phone것을 할 수 마지막으로 하실 수 .★★★★★★★★★★★★★★★★★★,csv다시 module을 클릭하여 파일을 열었을 때와 같은 형식으로 저장합니다.

판독용 코드:

import csv

with open("my_input_file.txt", "r") as f:
   reader = csv.reader(f, delimiter=":")
   lines = list(reader)

쓰기 코드:

with open("my_output_file.txt", "w") as f:
   writer = csv.writer(f, delimiter=":")
   writer.writerows(lines)

'아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 이런change()★★★★

def change(lines):
    a = input('ID')
    for line in lines:
      if line[0] == a:
        d=str(input("phone"))
        line[3]=d
        break
    else:
      print "not"

타이밍을 맞추지는 않았지만 h5가 피클보다 빠르다고 장담합니다. 압축된 파일 크기는 거의 확실히 작습니다.

import deepdish as dd
dd.io.save(filename, {'dict1': dict1, 'dict2': dict2}, compression=('blosc', 9))
file_name = open("data.json", "w")
json.dump(test_response, file_name)
file_name.close()

또는 콘텍스트 매니저를 사용하는 것이 좋습니다.

with open("data.json", "w") as file_name:
    json.dump(test_response, file_name)

언급URL : https://stackoverflow.com/questions/19201290/how-to-save-a-dictionary-to-a-file

반응형