Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python3中以二进制模式在.txt文件中保存多个数据类型的值?_Python_Python 3.x_Ubuntu 16.04_Python 3.5_Binaryfiles - Fatal编程技术网

如何在python3中以二进制模式在.txt文件中保存多个数据类型的值?

如何在python3中以二进制模式在.txt文件中保存多个数据类型的值?,python,python-3.x,ubuntu-16.04,python-3.5,binaryfiles,Python,Python 3.x,Ubuntu 16.04,Python 3.5,Binaryfiles,我试图以二进制模式将一组参数保存在文本文件中。通过单词set我的意思是将有两个值像一对一样。 例如-参数=重量,值=35。 我的密码是: with open(os.path.join(path, "parameters.txt"), "wb") as out: for parameter, value in parameters: out.write("{}: {}\n".format(bytearray(parameter,'utf-8'),(bytearray(val

我试图以二进制模式将一组参数保存在文本文件中。通过单词set我的意思是将有两个值像一对一样。
例如-参数=重量,值=35。
我的密码是:

with open(os.path.join(path, "parameters.txt"), "wb") as out:
    for parameter, value in parameters:
        out.write("{}: {}\n".format(bytearray(parameter,'utf-8'),(bytearray(value,'utf-8'))  
但主要问题是
value
中的值不是同一类型。它有
int、float、string、tuple
类型的值。使用上面的代码,我得到一个错误:

TypeError: a bytes-like object is required, not 'str'  
是否有一种以二进制模式保存
value
中的值的通用方法?i、 e
value

注意:我使用的是python 3.5和ubuntu 16.04


我想你可以用这样的东西:

import os
parameters = {"some": "some1", "some2": "some3", "1": 123, 123: 123}
s = ""
path = "."
########
to_s = lambda x: (str(x) if not isinstance(x, str) else x)   
with open(os.path.join(path, "parameters.txt"), "wb") as out:
    for parameter, value in parameters.items():
        s += "{}: {}\n".format(to_s(parameter), to_s(value))
    out.write(bytearray(s, 'utf-8'))

变量
parameters
已作为参数传递给函数,在该函数中,我正在编写上述代码(我文章中的代码)。所以我不能手动覆盖它。但是是的,您提到的
parameters={“some”:“some1”,“some2”:34,“some3”:(2,9)}
格式是正确的,只是很少有值是不同的数据类型。在这种情况下,您可以添加简单的函数将所有值转换为字符串。(我添加到示例中的“s”)上面的“代码”下的“助手”部分,用于检查脚本是否工作,您只需要在“二进制”和“文本”下的代码即可。。。如果文本很重要:如果需要元组,请查看pyyaml,如果不需要,请查看内部json模块。如果二进制更重要,请看一下msgpack。所谓“text”,我的意思是文件类型将是.txt文件,但所有写入操作都将以python的二进制模式进行。