简体   繁体   English

在 Python 中将字节列表写入文件

[英]Write byte list to a file in Python

I have a byte list as encrypted_message, which I have read from a file, like this:我有一个作为 encrypted_message 的字节列表,我从文件中读取了它,如下所示:

[b'\x17Q\xf7\xf8\x1b\xac\xc1\x05\x9cC\xc8)s\xb2x+p\xc5)@\xcc\x998\xd1P\x95
\xd8\xb9\xfaP\xe9\xeb!\x0c\xd9\xea\x04\xa7D\xddN\xc2\xfe\n', b'\x16p\xa6\x9d8
\xf3\xc4\x91^T\xbb\xac\x02t05\xbf\xcc6\x8a\xe5f\x11\xd2\xeaC,An\x7fw\x8f;
\xa5\xdf\x8f\xee\x87J\xb5W\xb0\xcf\x8e\x08\xfdGw\xa2?vYI\x0b\x99\xd7\xb7
\xce\xdfI\xb0\xb6\x00\x8b\xf8%\x11\xbc\xe2\xcb\xddA\x1b\xe6l\xd1\xe2\\\xf3
\rw\xa8s\xd8\x9b\xc5\\\xd7Yk\xc3\xb4\xe0\xde\xbdx\xe4\r\xf0G\x12/\x1a
\x17y\xc2\xaf\xb0\xe4\xa9\x02\xa7\xa9\xa6\x0fU\x89\xc1\xe1\x03ua\xd2F\xa7s
\x19K\xcf\x0c#\xb2\xe1<\x9d*\x1f8TF\xedX\xd4\x11g\x85\xb98\x15\xe3\x97
\xb8\x90_\x9ayM\x1e\xe6JW\x10\x97\xc1\x10\xc6\xb9\x1d\x9c \x16!\xb6M\x97Q\xe9
\xfe\n', b'\x9f\xbd\x0fA\xd2\x92\x10\x87u/H\xcb\xa9\x9e\x95\x80^\xf0Ll
\x8b\x81\xc3\x04\xb6F\xe4 \x9a\xd5\\&>>\xa1\x87{\xd3\xc3\xc7\x15D~\xd8\xd5
\x84\x1b@\xa5\x14\xfb5\x8a\xb0\xa5\xf1\x1aL{\xc9jW\x08Z2l\xb7\x0c\xb0\xce2
\x97\xb9\xdd\xc0%\xbf\x89q{\xd7\xa6l']

Now, I want to write this to another file.现在,我想将其写入另一个文件。 I am trying the following code:我正在尝试以下代码:

with open('encrypted_data.txt', 'wb') as temp_file:
    for item in enumerate(encrypted_message):
        temp_file.write(item)

But i keep getting the following error:但我不断收到以下错误:

TypeError: write() argument must be str, not tuple类型错误:write() 参数必须是 str,而不是元组

Can anyone help with this please?!任何人都可以帮忙吗?! Thank you in advance.先感谢您。

in之后删除enumerate然后它就可以工作了

enumerate returns tuples of (index, item) where index counts up from 0. You don't use the index so you don't need to use enumerate at all. enumerate返回(index, item)元组,其中index从 0 开始计数。您不使用索引,因此根本不需要使用enumerate

with open('encrypted_data.txt', 'wb') as temp_file:
    for item in encrypted_message:
        temp_file.write(item)

This such as common use case that the file object itself has a helper:这例如文件对象本身具有帮助程序的常见用例:

with open('encrypted_data.txt', 'wb') as temp_file:
    temp_file.writelines(encrypted_message)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM