要将文本文件转换为二进制形式,可以使用 Python 中的 open() 函数以二进制模式打开文件,并使用 read() 方法读取文件内容。然后,可以使用 open() 函数以二进制模式创建一个新文件,并使用 write() 方法将读取到的内容写入新文件中。

以下是一个示例代码:

def text_to_binary(input_file, output_file):
    with open(input_file, 'rb') as file:
        text = file.read()

    with open(output_file, 'wb') as file:
        file.write(text)

# 使用示例
input_file = 'input.txt'
output_file = 'output.bin'
text_to_binary(input_file, output_file)

在上述示例代码中,input_file 是要转换的文本文件的文件路径,output_file 是将要生成的二进制文件的文件路径。首先,我们使用 open() 函数以二进制模式打开输入文件,并使用 read() 方法读取文件内容并存储在 text 变量中。然后,我们使用 open() 函数以二进制模式创建一个新文件,并使用 write() 方法将 text 变量中的内容写入新文件中。

Python 将文本文件转换为二进制文件

原文地址: https://www.cveoy.top/t/topic/paBa 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录