티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.
Writing a dictionary to a text file?
딕셔너리를 텍스트 파일로 쓰는 방법?
문제 내용
I have a dictionary and am trying to write it to a file.
딕셔너리를 파일로 쓰고자 합니다.
exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'r') as file:
file.write(exDict)
I then have the error
그런 다음에 다음과 같은 오류가 발생합니다.
file.write(exDict)
TypeError: must be str, not dict
So I fixed that error but another error came
그래서 해당 오류를 수정했는데 다른 오류가 발생했습니다.
exDict = {111:111, 222:222}
with open('file.txt', 'r') as file:
file.write(str(exDict))
The error:
해당 오류는 다음과 같습니다:
file.write(str(exDict))
io.UnsupportedOperation: not writable
How do I resolve this issue?
어떻게 이 문제를 해결할 수 있을까요?
높은 점수를 받은 Solution
First of all you are opening file in read mode and trying to write into it. Consult - IO modes python
우선, 파일을 읽기 모드로 열고 쓰려고 시도하고 있습니다. 파이썬의 IO 모드를 확인하십시오.
Secondly, you can only write a string or bytes to a file. If you want to write a dictionary object, you either need to convert it into string or serialize it.
둘째, 파일에 쓰려면 문자열 또는 바이트만 쓸 수 있습니다. 딕셔너리 객체를 쓰려면 문자열로 변환하거나 직렬화해야합니다.
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
In case of serialization
직렬화의 경우
import cPickle as pickle
with open('file.txt', 'w') as file:
file.write(pickle.dumps(exDict)) # use `pickle.loads` to do the reverse
For python 3.x pickle package import would be different
파이썬 3.x에서는 pickle 패키지 임포트가 다릅니다.
import _pickle as pickle
가장 최근 달린 Solution
For list comprehension lovers, this will write all the key : value
pairs in new lines in dog.txt
리스트 내포를 좋아하는 사람들을 위해, 이 코드는 dog.txt에 모든 key:value 쌍을 새 줄로 작성합니다.
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 ]
출처 : https://stackoverflow.com/questions/36965507/writing-a-dictionary-to-a-text-file
'개발 > 파이썬' 카테고리의 다른 글
사전에 값이 있는지 확인하기 (0) | 2023.02.24 |
---|---|
파이썬에서 두 개의 리스트를 비교하고 일치하는 값을 반환하는 방법 (0) | 2023.02.24 |
Python에서 파일이 이진 파일(텍스트가 아님)인지 아닌지 확인하는 방법 (0) | 2023.02.22 |
Python 사전(dictionary)에서 값에 대해 매핑(mapping)하는 방법 (0) | 2023.02.22 |
DataFrame의 문자열 열을 datetime으로 변환하기 (0) | 2023.02.22 |