Python解密文件类型错误的问题

Python解密文件类型错误的问题,python,python-3.x,list,Python,Python 3.x,List,我最近得到了一个Python脚本来解密Excel文件。我以前没有任何使用Python的经验,所以我一直在试图找出如何通过Google搜索正确运行脚本,但我遇到了麻烦。据我所知,这个脚本已经有几年的历史了,可能不是Python3的最新版本 from StringIO import StringIO import os import tkFileDialog def crypt(t, k): old = StringIO(t) new = StringIO(t)

我最近得到了一个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
回溯(最近一次呼叫最后一次):
文件“/Users/xxx/Desktop/App/Decrypt.py”,第34行,在
f_out.write(crypt(f_in.read(),key))
文件“/Users/xxx/Desktop/App/Decrypt.py”,第9行,在crypt中
old=StringIO(t)
TypeError:初始值必须是str或None,而不是bytes
不知道如何处理此错误-将感谢任何帮助或建议

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

另请参见:

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

为了将字节转换为字符串,以便使用另一个函数,您有两个选项:

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

此外,考虑到上面的内容,请注意如何将内容写入输出文件(以字节或字符串)。

如果你想这样回答你的问题,请考虑接受答案并对其进行投票,以便将来的用户能够更容易地找到答案。