[python-3.x] 텍스트 파일에 사전 쓰기?

사전이 있고 파일에 쓰려고합니다.

exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'r') as file:
    file.write(exDict)

그런 다음 오류가 있습니다.

file.write(exDict)
TypeError: must be str, not dict

그래서 그 오류를 수정했지만 또 다른 오류가 발생했습니다.

exDict = {111:111, 222:222}
with open('file.txt', 'r') as file:
    file.write(str(exDict))

오류:

file.write(str(exDict))
io.UnsupportedOperation: not writable

나는 아직도 파이썬 초보자이기 때문에 무엇을 해야할지 모르겠다. 문제를 해결하는 방법을 아는 사람이 있으면 답변을 제공하십시오.

참고 : 저는 파이썬 2가 아닌 파이썬 3을 사용하고 있습니다.



답변

우선 읽기 모드에서 파일을 열고 쓰기를 시도합니다. Consult- IO 모드 Python

둘째, 파일에 문자열 만 쓸 수 있습니다. 사전 객체를 작성하려면 문자열로 변환하거나 직렬화해야합니다.

import json

# as requested in comment
exDict = {'exDict': exDict}

with open('file.txt', 'w') as file:
     file.write(json.dumps(exDict)) # use `json.loads` to do the reverse

직렬화의 경우

import cPickle as pickle

with open('file.txt', 'w') as file:
     file.write(pickle.dumps(exDict)) # use `pickle.loads` to do the reverse

Python 3.x의 경우 pickle 패키지 가져 오기가 다를 수 있습니다.

import _pickle as pickle


답변

나는 파이썬 3에서 이렇게한다.

with open('myfile.txt', 'w') as f:
    print(mydictionary, file=f)


답변

fout = "/your/outfile/here.txt"
fo = open(fout, "w")

for k, v in yourDictionary.items():
    fo.write(str(k) + ' >>> '+ str(v) + '\n\n')

fo.close()


답변

첫 번째 코드 블록을 사용하는 프로브는 'w'

with open('/Users/your/path/foo','w') as data:
    data.write(str(dictionary))


답변

파일에서 이름으로 가져올 수 있고 잘 정렬되고 보존하려는 문자열이 포함 된 항목을 추가 할 수있는 사전을 원한다면 다음을 시도 할 수 있습니다.

data = {'A': 'a', 'B': 'b', }

with open('file.py','w') as file:
    file.write("dictionary_name = { \n")
    for k in sorted (data.keys()):
        file.write("'%s':'%s', \n" % (k, data[k]))
    file.write("}")

그런 다음 가져 오기 :

from file import dictionary_name


답변

목록 이해력 애호가를 위해 이것은 모든 key : value쌍을 새 줄로 작성합니다.dog.txt

my_dict = {'foo': [1,2], 'bar':[3,4]}

# create list of strings
list_of_strings = [ f'{key} : {my_dict[key]}' for key in my_dict ]

# write string one by one adding newline
with open('dog.txt', 'w') as my_file:
    [ my_file.write(f'{st}\n') for st in list_of_strings ]


답변

나는 이것이 오래된 질문이라는 것을 알고 있지만 json을 포함하지 않는 솔루션을 공유하려고 생각했습니다. 데이터를 쉽게 추가 할 수 없기 때문에 개인적으로 json을 좋아하지 않습니다. 시작점이 사전 인 경우 먼저 데이터 프레임으로 변환 한 다음 txt 파일에 추가 할 수 있습니다.

import pandas as pd
one_line_dict = exDict = {1:1, 2:2, 3:3}
df = pd.DataFrame.from_dict([one_line_dict])
df.to_csv('file.txt', header=False, index=True, mode='a')

도움이 되었기를 바랍니다.