Python将文本文件读取为二进制文件? [英] Python read text file as binary?

查看:615
本文介绍了Python将文本文件读取为二进制文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在python 2.7中构建一个加密程序.它将从文件中读取二进制文件,然后使用密钥对其进行加密.但是,我很快遇到了一个问题.图像文件和可执行文件之类的文件读取为十六进制值.但是,文本文件不使用open().即使我跑

I was trying to build an encryption program in python 2.7. It would read the binary from a file and then use a key to encrypt it. However, I quickly ran into a problem. Files like image files and executables read as hex values. However, text files do not using open(). Even if i run

file = open("myfile.txt","rb")

file=open("myfile.txt", "rb")

out = file.read()

out=file.read()

它仍然只是文本出现.我在Windows 7上,而不是Linux上,我认为这可能会有所作为.我有什么办法可以从任何文件(包括文本文件)中读取二进制文件,而不仅仅是图像和可执行文件?

it still comes out as just text. I'm on windows 7, not linux which i think may make a difference. Is there any way i could read the binary from ANY file (including text files), not just image and executable files?

推荐答案

即使在读取带有'rb'标志的文件时, 如果您的文件具有字节"\ x41",它将在控制台中打印为字母"A". 如果需要十六进制值,请将文件内容编码为十六进制,这表示:

Even when reading a file with the 'rb' flag, if your file has the byte '\x41' it will be printed as the letter 'A' in the console. If you want the hex values, encode the file content as hex, which means:

content = open('text.txt', 'rb').read()
hex = content.encode('hex')

这篇关于Python将文本文件读取为二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆