[英]Python adds unicode to file
Im writing a default dict (list) to a file with :我正在将默认字典(列表)写入文件:
def write_to_file(slack_dict):
if os.path.exists("slack_dict"):
print ("slack_dict file already exist, skipping writing")
else:
print ("writing slack_dict to file")
F = open('slack_dict', "w")
F.write(str(slack_dict).encode('UTF-8'))
F.close()
the slack_dict being written to file is :写入文件的 slack_dict 是:
defaultdict(<type 'list'>, {u'djin_acontentmgmt_sample': [{'color': u'blue',
'status': 'SUCCESS', 'region': u'virginia', 'env': u'int', 'job_no': '122'}]})
How do I remove the unicode strings ?如何删除 unicode 字符串? I already have tried F.write(str(slack_dict).encode('UTF-8'))
我已经尝试过F.write(str(slack_dict).encode('UTF-8'))
If I do the following, there are no non-ASCII characters in the 'slack_dict' file, since there are no non-ASCII characters in any of the 'Unicode' strings in the dictionary.如果我执行以下操作,则 'slack_dict' 文件中没有非 ASCII 字符,因为字典中的任何 'Unicode' 字符串中都没有非 ASCII 字符。 Everything is stored exactly as shown (eg, a literal 'u', not a non-ASCII character).一切都完全按照所示存储(例如,文字“u”,而不是非 ASCII 字符)。
from collections import defaultdict
slack_dict = defaultdict(list)
slack_dict[u'djin_acontentmgmt_sample'] = [
{'color': u'blue', 'status': 'SUCCESS', 'region': u'virginia', 'env': u'int', 'job_no': '122'}
]
with open('slack_dict', 'w') as f:
f.write(str(slack_dict).encode('UTF-8'))
with open('slack_dict', 'r') as f:
print f.read()
# defaultdict(<type 'list'>, {u'djin_acontentmgmt_sample': [{'color': u'blue', 'status': 'SUCCESS', 'region': u'virginia', 'env': u'int', 'job_no': '122'}]})
Are you trying to eliminate the 'u' markers, eg, to write json text?您是否试图消除“u”标记,例如,编写 json 文本? In that case, you could try this:在这种情况下,你可以试试这个:
import json
with open('slack_dict', 'w') as f:
json.dump(slack_dict, f)
# equivalent to f.write(json.dumps(slack_dict))
with open('slack_dict', 'r') as f:
print f.read()
# {"djin_acontentmgmt_sample": [{"color": "blue", "status": "SUCCESS", "region": "virginia", "env": "int", "job_no": "122"}]}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.