解码功能中python2和python3之间的区别

时间:2018-08-15 04:30:34

标签: python python-3.x python-2.7

最近,我观看了一段有关编写代码以将文件标题和内容从十进制数字解码为字符串的视频。但是,它是用python2编写的,所以我决定用python3重写代码。不幸的是,我在解码图片内容时遇到了麻烦。

这是python2中的原始代码:

#!/usr/bin/env python

import os

directory = '1262404985085867488371'

def decrypt(number): 
    return hex(int(number))[2:].replace("L","").decode("hex")


os.chdir(directory)
for i in os.listdir('.'):
    try:
        print(decrypt(i))
        c = open(i).read()
        open(decrypt(i),'w').write(decrypt(c))
        #o.write(decrypt(c))

    except:
        print("FAILED WITH",i)

这是用python3编写的代码:

#!/usr/bin/env python3

import os

directory = '1262404985085867488371'

def decrypt(number): 
    hex_num = hex(int(number))[2:].replace("L","")
    return  bytes.fromhex(hex_num).decode("ascii")


os.chdir(directory)
for i in os.listdir('.'):
    try:
        print(decrypt(i))
        c = open(i).read()
        open(decrypt(i),'w').write(decrypt(c))
        #o.write(decrypt(c))

    except:
        print("FAILED WITH",i)

任何人都可以帮助我看看如何解决此问题吗?这是关于以下问题:

  

我的计算机感染了勒索软件,现在无法访问我的任何文档!如果您帮助我,我会奖励您一个标志!   https://static.tjctf.org/7459b0c272ba30c9fea94391c7d7051d78e1732c871c3a6f27070fcb34f9e734_encrypted.tar.gz

基本上,我尝试过将ascii更改为utf-8,并使用“ wb”或“ rb”模式打开文件,但它们都不起作用...

1 个答案:

答案 0 :(得分:1)

我要开枪了,因为您没有提供任何示例和/或错误,所以我想您会遇到这种错误:

EXECUTE

这是由具有Unicode名称的文件\目录引起的,当您尝试使用Traceback (most recent call last): File "<stdin>", line 1, in <module> UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position 0: ordinal not in range(128) 中的ascii进行解码时,该目录又触发了此异常。

相反,请尝试使用“ utf-8”解码。