本文介绍了在 Windows 上防止 Python print() 自动换行转换为 CRLF的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过 Windows CMD(控制台)从 Python 使用类 Unix EOL (LF) 传输文本.但是,Python 似乎会自动将单个换行符转换为 Windows 样式的 行尾 (EOL) 字符(即 \r\n0D 0A13 10>):

#!python3#coding=utf-8导入系统打印(系统版本)打印(一个\n两个")# 作为 py t.py 运行 >t.txt

结果

3.6.5 (v3.6.5:f59c0932b4, Mar 28 2018, 17:00:18) [MSC v.1900 64 位 (AMD64)]一二

或十六进制 ... 6F 6E 65 0D 0A 74 77 6F 0D 0A

第二次 EOL 是因为print() 默认为 end='\n',但它也进行转换.

没有像 open() 那样用于打印的 newline 参数或属性,那么如何控制?

解决方案

Warning: See eryksun's comment below, this requires some care. Use his solution instead (link below):


It seems it might also be possible to reopen the file, see Wrap an open stream with io.TextIOWrapper for inspiration, and this answer https://stackoverflow.com/a/34997357/1619432 for the implementation.


If you want to take a closer look, check out the Python (CPython) sources:https://github.com/python/cpython/blob/master/Modules/_io/textio.c


There's also os.linesep, let's see if it's really "\r\n" for Windows:

>>> import os
>>> os.linesep
'\r\n'
>>> ",".join([f'0x{ord(c):X}' for c in os.linesep])
'0xD,0xA'

Could this be redefined?

#!python3
#coding=utf-8
import sys, os
saved = os.linesep
os.linesep = '\n'
print(os.linesep)
print("one\ntwo")
os.linesep = saved

It can in the interactive mode, but apparently not otherwise:

\r\n
\r\n
one\r\n
two\r\n


这篇关于在 Windows 上防止 Python print() 自动换行转换为 CRLF的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 14:15