0
我试图将要编码的策略文档传递给base64。在Python中传递JSON文档
的政策文件位于~/policy_document
>>> policy = base64.b64encode(policy_document)
什么我需要在这里做的就是policy_document
将它传递为Base64?谢谢。
我试图将要编码的策略文档传递给base64。在Python中传递JSON文档
的政策文件位于~/policy_document
>>> policy = base64.b64encode(policy_document)
什么我需要在这里做的就是policy_document
将它传递为Base64?谢谢。
# First open the file
# Then read the entire contents into memory
>>> policy_document = open("/absolute/path/to/policy_document", "r").read()
# Then base64 encode the contents.
>>> policy = base64.b64encode(policy_document)
# If you are using Python 2.7 you can use the with statement
# to ensure files are cleaned up
# (See @Niklas' comment)
>>> with open("/absolute/path/to/policy_document", "r") as fp:
... policy_document = fp.read()
... policy = base64.b64encode(policy_document)
# fp will be properly closed
另外,如果你需要它是从当前用户的主文件夹,你可以添加一个调用os.path.expanduser("~/policy_document")
这为我工作:
policy = base64.b64encode(json.JSONEncoder().encode({dict})
你可能还想在事后关闭文件,或者在Python 2.7中使用'with open(...)as file:'语句,具体取决于脚本是否在操作之后立即终止。 –
我从'read()'调用中删除了'-1',因为它没有添加任何内容,只是使它变得混乱(来自'help(file)':“如果size参数为负数或省略,请阅读,直至到达EOF。 )。 –
@尼克拉斯:请不要'作为文件'; 'file'是一个内建的。 –