TypeError:不带编码的字符串参数

Pro*_*120 9 python google-cloud-storage google-cloud-platform google-cloud-datalab

我想将Json的压缩gzip上传到Google Storage。

我有以下代码:

import datalab.storage as storage
import gzip
path = prefix + '/orders_newline.json.gz'
storage.Bucket('orders').item(path).write_to(gzip.compress(bytes(create_jsonlines(source)),encoding='utf8'), 'application/json')
Run Code Online (Sandbox Code Playgroud)

create_jsonlines(source)是返回的Json换行符分隔的功能。

运行这段代码可以得到:

TypeError: string argument without an encoding
Run Code Online (Sandbox Code Playgroud)

Python文档说,格式是:bytes([source[, encoding[, errors]]])我不知道我把它理解为不存在如何使用它的例子。

我也尝试过

bytes([(create_jsonlines(source))[,encoding='utf8']])
Run Code Online (Sandbox Code Playgroud)

这给出了:

SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

我正在运行Python 3.5

Bla*_*der 13

您没有bytes正确使用该功能。检查一下:

>>> a = "hi"
>>> bytes(a, encoding='utf8')
b'hi'
Run Code Online (Sandbox Code Playgroud)

你可以试试:

bytes((create_jsonlines(source)), encoding='utf8')
Run Code Online (Sandbox Code Playgroud)

encoding是该bytes函数的参数,而您正在该函数之外使用它。

  • 你可以只执行“str.encode()”而不指定编码 (2认同)

lin*_*ncr 6

你可能离答案只有一步之遥。

请参阅bytearray()bytes以了解函数用法(您可能需要更改文档的 python 版本)。

它说:

可选的 source 参数可用于以几种不同的方式初始化数组:

  • 如果是字符串,还必须给出编码(和可选的错误)参数;bytearray() 然后使用 str.encode() 将字符串转换为字节。
  • 如果它是一个整数,则该数组将具有该大小并使用空字节进行初始化。
  • 如果是符合buffer接口的对象,则使用该对象的只读缓冲区来初始化bytes数组。
  • 如果它是可迭代的,则它必须是 0 <= x < 256 范围内的整数的可迭代,这些整数用作数组的初始内容。

注意方括号表示这些参数可以省略,它不是python语言的数组类型。

所以你应该使用bytes(create_jsonlines(source), encoding='utf8').