如何将包含文本和十六进制值的列表写入文件?

0 投票
2 回答
1282 浏览
提问于 2025-04-17 19:00

我需要把一串数值写入一个文本文件。因为在Windows系统中,当我需要写入换行符时,它使用的是\n\r,而其他系统则只用\n。

我想,也许我应该以二进制的方式写入文件。

我该如何创建一个像下面这个例子的列表,并以二进制的方式写入文件呢?

output = ['my first line', hex_character_for_line_feed_here, 'my_second_line']

为什么下面的代码不行呢?

output = ['my first line', '\x0a', 'my second line']

2 个回答

1

在和你的Python脚本同一个文件夹里,创建一个文本文件,叫“myTextFile”。然后写一些类似下面的内容:

# wb opens the file in "Write Binary" mode
myTextFile = open("myTextFile.txt", 'wb')

output = ['my first line', '369as3', 'my_second_line']

for member in output:
    member.encode("utf-8") # Or whatever encoding you like =)
    myTextFile.write(member + "\n")

这样会输出一个二进制文本文件,内容看起来像这样:

my first line
369as3
my_second_line

补充说明:已更新为Python 3版本

3

不要这样做。直接以文本模式打开文件,让Python自己处理换行符。

当你使用open()函数时,可以通过newline这个参数来设置Python如何处理换行符:

在向流中写入内容时,如果newlineNone,那么写入的任何'\n'字符都会被转换为系统默认的换行符os.linesep。如果newline''或者'\n',那么就不会进行转换。如果newline是其他合法值,那么写入的'\n'字符会被转换为指定的字符串。

所以默认情况下,Python会为你的平台写入正确的换行符:

with open(outputfilename, 'w') as outputfile:
    outputfile.write('\n'.join(output))

这样做是正确的;在Windows上,会保存\r\n字符,而不是\n

如果你特别想只写\n,而不让Python为你转换,可以使用newline=''

with open(outputfilename, 'w', newline='') as outputfile:
    outputfile.write('\n'.join(output))

注意,'\x0a'\n完全相同的字符;\r\x0d

>>> '\x0a'
'\n'
>>> '\x0d'
'\r'

撰写回答