Как записать в файл и считать символы типа "\n"
Есть словарь {символ: код}, нужно вписать в файл и считать в такой же словарь, однако не понятно как быть с символами типа '\n' '\r'? Код:
code_in = {'\n': '100110', '\t': '0101011', 'a': '0101010'}
code_out = {}
with open('file.txt','w', encoding='cp866') as f:
for key,val in code_in.items():
f.write('{}:{}\n'.format(key,val))
with open('file.txt', 'r', encoding='cp866') as f:
for i in f.readlines():
key,val = i.strip().split(':')
code_out[key] = val
Ответы (1 шт):
Автор решения: Daniil Loban
→ Ссылка
import json
code_in = {'\n': '100110', '\t': '0101011', 'a': '0101010'}
code_out = {}
formated = json.dumps(code_in}, sort_keys=True, indent=0)
#запись
with open('dict.txt', 'w', encoding='cp866') as f:
f.write(formated[2:-2])
print(formated)
#чтение
with open('dict.txt', 'r', encoding='cp866') as f:
file_content = f.read()
code_out = json.loads('{' + file_content + '}')
print(code_out)


