Skip to main content
 首页 » 编程设计

python之0 写入文件时出现十六进制错误

2025年05月04日10insus

我有一个小问题: 为什么这段代码

somefile = open('foo.txt', 'w') 
somefile.write('0B0B0B'.decode('hex')) 
somefile.close() 

在文件中写入0B0B0B,以及这段代码

somefile = open('foo.txt', 'w') 
somefile.write('0A0A0A'.decode('hex')) 
somefile.close() 

在文件中写入 0D0A0D0A0D0A? “0D”从何而来?

请您参考如下方法:

它来自 \n -> \r\n 转换,因为您在 Windows 上运行。如果您想避免这种情况,请以二进制模式 ('wb') 打开文件。