Nice programing

텍스트 파일에 사전 쓰기?

nicepro 2021. 1. 5. 21:09
반응형

텍스트 파일에 사전 쓰기?


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

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()

첫 번째 코드 블록을 사용한 프로브는 다음을 사용하여 작성하고 싶었지만 파일을 'r'로 여는 것입니다. 'w'

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

If you want a dictionary you can import from a file by name, and also that adds entries that are nicely sorted, and contains strings you want to preserve, you can try this:

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("}")

Then to import:

from file import dictionary_name

I know this is an old question but I also thought to share a solution that doesn't involve json. I don't personally quite like json because it doesn't allow to easily append data. If your starting point is a dictionary, you could first convert it to a dataframe and then append it to your txt file:

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')

I hope this could help.


import json exDict = {1:1, 2:2, 3:3} file.write(json.dumps(exDict))

https://developer.rhino3d.com/guides/rhinopython/python-xml-json/


import json

with open('tokenler.json', 'w') as file:
     file.write(json.dumps(mydict, ensure_ascii=False))

ReferenceURL : https://stackoverflow.com/questions/36965507/writing-a-dictionary-to-a-text-file

반응형