【问题标题】:Issues with Python decrypt file - type errorPython解密文件的问题 - 类型错误
【发布时间】:2020-11-23 06:33:21
【问题描述】:

我最近收到了一个 Python 脚本来解密 Excel 文件。我之前没有任何使用 Python 的经验,所以我一直在试图弄清楚如何通过 Google 搜索正确运行脚本,但我碰壁了。据我所知,该脚本已有几年历史了,对于 Python3 可能不是最新的。

from StringIO import StringIO
import os
import tkFileDialog

def crypt(t, k):
    old = StringIO(t)
    new = StringIO(t)
    
    for position in xrange(len(t)):
        bias = ord(k[position % len(k)])
        
        old_char = ord(old.read(1))
        new_char = chr(old_char ^ bias)
        
        new.seek(position)
        new.write(new_char)
    
    new.seek(0)
    return new.read()


dirname = tkFileDialog.askdirectory(initialdir="/",  title='Please select a directory')
files = [f for f in os.listdir(dirname) if os.path.join(dirname, f)]
for f in files:
    t = os.path.join(dirname, f)
    tout = os.path.join(dirname, 'decr_%s' % f)
    
    f_in = open(t, 'rb')
    f_out = open(tout, 'wb')
    key = "b8,xaA3rvXb-d&w8P6!9k7dQs.dbkLEw?t!3!`sM(,f!2^6h"
    f_out.write(crypt(f_in.read(), key))
    f_in.close()
    f_out.close()

这是我第一次得到的脚本。在几个 ModuleNotFoundErrors 和 AttributeErrors 之后,我尝试进行更改。现在,出现的错误是:

Traceback (most recent call last):
  File "/Users/xxx/Desktop/App/Decrypt.py", line 34, in <module>
    f_out.write(crypt(f_in.read(), key))
  File "/Users/xxx/Desktop/App/Decrypt.py", line 9, in crypt
    old = StringIO(t)
TypeError: initial_value must be str or None, not bytes

不确定如何处理此错误 - 非常感谢任何帮助或建议!

【问题讨论】:

    标签: python python-3.x list


    【解决方案1】:

    f_in.read() 从文件中读取字节,StringIO 不能将字节值作为初始值处理。您可以将 bytes 变量转换为 str 变量并在 StringIO 构造函数中使用它。

    另见:Convert bytes to a string

    【讨论】:

      【解决方案2】:

      file.open() 函数有 'rb' 参数,它指定它将以字节形式读取文件的内容。

      为了将字节转换为字符串,以便可以使用其他功能,您有两种选择:

      • 使用decode("utf-8") 函数。请注意,您使用的数据的编码确实是 utf-8,否则请指定您的数据正在使用的编码。
        您的线路应该是:f_out.write(crypt(f_in.read().decode("utf-8"), key))
      • 如果您确定文件仅包含文本,则可以省略 'b' 参数并仅使用 f_in = open(t, 'r')。这将以文本模式打开并读取文件,这意味着您可以直接以字符串的形式读取内容。

      此外,考虑到上述情况,请注意将内容写入输出文件的方式(作为字节或字符串)。

      【讨论】:

      • 如果您觉得这回答了您的问题,请考虑接受答案并点赞,以便未来的用户能够更轻松地找到它。
      猜你喜欢
      • 2010-09-24
      • 1970-01-01
      • 1970-01-01
      • 2012-04-14
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多