简体   繁体   English

Python如何从文本文件制作可执行文件

[英]Python how to make an executable from a text file

So what i want to do is write a .exe bynary to a .txt file and then write the .txt file to a .exe bynary, i tried this: 因此,我想做的是将.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()

but if i run the New_File.exe windows tels me it is not a valid aplication. 但是如果我运行New_File.exe Windows给我New_File.exe那不是有效的应用程序。 What am doing wrong? 怎么了?

The answer is: 答案是:

The second time you were reading the *.txt file, you didn't open it in read binary mode, just in read, which is in fact, read text mode. 第二次阅读* .txt文件时,您没有以读取二进制模式打开它,而是以读取(实际上是读取文本模式)打开了它。 With older versions of Python it was platform dependent, ie this will be a problem only on Windows. 在旧版本的Python中,它依赖于平台,即仅在Windows上才是问题。 In Python 3, this will make you a problem on any platform. 在Python 3中,这将使您在任何平台上都遇到问题。

Advice: Don't read a file in so small chunks if you don't have to, you will throttle poor Windows. 忠告:如果不需要,请不要小块地读取文件,否则将限制可怜的Windows。 Do it with at least 1024. It's often done with 4096 bytes. 至少需要1024个字节。通常需要4096个字节。 If the file is small, just do newfile.write(oldfile.read()) Todays PCs have enough RAM to put few MB in it without any problem. 如果文件很小,那么只需执行newfile.write(oldfile.read())即可。今天的PC有足够的RAM可以在其中放入几MB的内存,而不会出现任何问题。 And, there is no need for str(byte) as it is already a string. 并且,因为它已经是一个字符串,所以不需要str(byte)。

To copy two files and preserve metadata, use shutil.copy2 . 要复制两个文件并保留元数据,请使用shutil.copy2 This is a much safer way to copy files. 这是复制文件的更安全的方法。

i foud the answer myself: 我自己回答这个问题:

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()

you actually have to write the binary on the text file instead of writing it as a string on the file itself. 您实际上必须将二进制文件写入文本文件,而不是将其作为字符串写入文件本身。

    #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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM