似乎有两种不同的方法将字符串转换为字节,如TypeError的答案所示:'str'不支持缓冲区接口
哪种方法更好或更好Pythonic?或者只是个人喜好?
b = bytes(mystring, 'utf-8')
b = mystring.encode('utf-8')
Run Code Online (Sandbox Code Playgroud) 我正在尝试通过子进程流式传输数据,将其 gzip 并写入文件。以下作品。我想知道是否可以使用 python 的本机 gzip 库来代替。
fid = gzip.open(self.ipFile, 'rb') # input data
oFid = open(filtSortFile, 'wb') # output file
sort = subprocess.Popen(args="sort | gzip -c ", shell=True, stdin=subprocess.PIPE, stdout=oFid) # set up the pipe
processlines(fid, sort.stdin, filtFid) # pump data into the pipe
Run Code Online (Sandbox Code Playgroud)
问题:我该怎么做……在使用 python 的 gzip 包的地方?我很想知道为什么下面给了我一个文本文件(而不是一个压缩的二进制版本)......很奇怪。
fid = gzip.open(self.ipFile, 'rb')
oFid = gzip.open(filtSortFile, 'wb')
sort = subprocess.Popen(args="sort ", shell=True, stdin=subprocess.PIPE, stdout=oFid)
processlines(fid, sort.stdin, filtFid)
Run Code Online (Sandbox Code Playgroud) 虽然此代码读取和写入 jsonlines 文件。怎么压缩呢?我尝试直接使用gzip.open
,但出现各种错误。
import json
def dump_jsonl(data, output_path, append=False):
"""
Write list of objects to a JSON lines file.
"""
mode = 'a+' if append else 'w'
with open(output_path, mode, encoding='utf-8') as f:
for line in data:
json_record = json.dumps(line, ensure_ascii=False)
f.write(json_record + '\n')
print('Wrote {} records to {}'.format(len(data), output_path))
def load_jsonl(input_path) -> list:
"""
Read list of objects from a JSON lines file.
"""
data = []
with open(input_path, 'r', encoding='utf-8') as f:
for line in f: …
Run Code Online (Sandbox Code Playgroud)