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 :
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 ? I already have tried 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. Everything is stored exactly as shown (eg, a literal 'u', not a non-ASCII character).
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? 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"}]}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.