[从python2移植到python3时出现文件IO错误]

2024-04-28 21:55:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我将我的项目从python2.7移植到python3.6

我在Python2.7中所做的

1)从基64解码

2)使用Gzip解压

3)逐行读取外接程序文件

    bytes_array = base64.b64decode(encryptedData)
    fio = StringIO.StringIO(bytes_array)
    f = gzip.GzipFile(fileobj=fio)
    decoded_data = f.read()
    f.close()
    f = file("DecodedData.log",'w')
    for item in decoded_data:
        f.write(item)
    f.close()

我用python3的修改尝试了同样的方法,但是不管出现哪种错误都不起作用。你知道吗

我不能使用StringIO,因为我有错误

#initial_value must be str or None, not bytes

所以我试试这个

    bytes_array = base64.b64decode(encryptedData)

    #initial_value must be str or None, not bytes

    fio = io.BytesIO(bytes_array)
    f = gzip.GzipFile(fileobj=fio)
    decoded_data =f.read()
    f= open("DecodedData.log",'w')
    for item in decoded_data:

        f.write(item)
    f.close()

这在f.write(item)行中给出了错误

    write() argument must be str, not int

令我惊讶的是,当我打印它时,它实际上包含一个整数

我想,既然我没有给出极限,那就是尽可能多地阅读。 所以我试着逐行读取文件

   f= open("DecodedData.log",'w')
   with open(decoded_data) as l:
    for line in l:    
        f.write(line)

但它仍然不起作用,而且\n还在文件中打印。 有人能告诉我缺少什么吗。你知道吗


Tags: 文件inlogforclosedatabytes错误
1条回答
网友
1楼 · 发布于 2024-04-28 21:55:28
decoded_data = f.read()

将导致解码的数据成为bytes对象。bytes对象是可iterable的,当您迭代它们时,它们将以整数(0-255)的形式返回数据中的每个字节值。也就是说当你这么做的时候

for item in decoded_data:
    f.write(item)

那么item将是原始数据中的每个整字节值。你知道吗

f.write(decoded_data)

您已经以文本模式打开了f,因此如果您想将原始二进制数据写入它,就需要以二进制模式打开它。但事实上,您已经调用了文件DecodedData.log,这表明您希望它是一个(人类可读的?)文本文件。你知道吗

所以我认为总的来说这会更具可读性:

gzipped_data = base64.b64decode(encryptedData)
data = gzip.decompress(gzipped_data)  
with open("DecodedData.log",'wb') as f:
    f.write(data)

根本不需要中间字节,gzip有一个解压缩方法(https://docs.python.org/3/library/gzip.html#gzip.decompress

相关问题 更多 >