Python 如何从文本文件生成可执行文件

Python how to make an executable from a text file

所以我想做的是将 .exe 二进制文件写入 .txt 文件,然后将 .txt 文件写入 .exe 二进制文件,我试过这个:

with open("old_File.exe", "rb") as f:
    text_file = open("File.txt", "w")
    byte = f.read(1)
    while byte != "":
        text_file.write(str(byte))
        byte = f.read(1)
text_file.close()

with open("New_File.exe", "wb") as f:
    text_file = open("File.txt", "r")
    byte = text_file.read(12)
    while byte != "":
        print byte
        f.write(byte)
        byte = text_file.read(12)
text_file.close()
f.close()

但是如果我 运行 New_File.exe windows 告诉我它不是有效的应用程序。 哪里做错了?

要复制两个文件并保留元数据,请使用 shutil.copy2。这是一种更安全的文件复制方式。

答案是:

第二次读取*.txt文件时,没有以读取二进制方式打开,只是以读取方式打开,其实就是读取文本方式。 对于旧版本的 Python,它依赖于平台,也就是说,这只会在 Windows 上出现问题。 在Python 3,这会让你在任何平台上都有问题。

建议:如果没有必要,请不要读取如此小的文件块,否则会导致性能下降 Windows。至少用1024来做。通常用4096字节来做。如果文件很小,只需执行 newfile.write(oldfile.read()) 今天的 PC 有足够的 RAM 可以毫无问题地放入几 MB。 而且,不需要 str(byte) 因为它已经是一个字符串。

我自己找到了答案:

exe = open("exe.exe", "rb")
txt = open("txt.txt", "wb")
data = exe.read(100000)
while data != "":
    txt.write(data)
    data = exe.read(100000)
exe.close()
txt.close()

您实际上必须将二进制文件写入文本文件,而不是将其作为字符串写入文件本身。

    #create new file
N_exe = open("N-exe.exe", "w+")
N_exe.close()


N_exe = open("N-exe.exe", "wb")
Txt = open("txt.txt", "rb")

data = Txt.read(100000)
while data != "":
    N_exe.write(data)
    data = Txt.read(100000)

N_exe.close()
Txt.close()