【问题标题】:Python not working properly with carriage returns (new line) [duplicate]Python无法正常使用回车符(新行)[重复]
【发布时间】:2020-09-27 14:05:47
【问题描述】:

根据python的官方文档,3.x及以上版本删除了读取文件的“U”参数,默认包含对不同回车的通用支持。但是,这不适用于最新版本 (3.8.6)。

file1 = open('cube_demo.gcode', 'rt') 
Lines = file1.readlines() 

  
count = 0
for line in Lines: 
    print(line)
    count += 1

我希望得到类似这样的输出:

G92 E0 ; reset extrusion distance
; Filament gcode
M104 S235

G1 Z0.250 F10800.000 ; move to next layer (0)
G1 E-7.00000 F3300.00000 ; retract
G92 E0 ; reset extrusion distance

但我明白了:

G92 E0 ; reset extrusion distance

; Filament gcode

M104 S235


G1 Z0.250 F10800.000 ; move to next layer (0)

G1 E-7.00000 F3300.00000 ; retract

G92 E0 ; reset extrusion distance

为什么会这样?根据How can I remove carriage return from a text file with Python?,python 现在支持通用换行符。另外: PEP 278 -- Universal Newline Support

那么我错过了什么?我不想剥离任何东西,因为这需要我首先弄清楚每个文件使用哪个回车符。由于此脚本适用于每个操作系统,因此这是必需的。

那么如何让这种通用支持按预期工作?

很奇怪,我看到很多话题,和这个很相似。但实际上没有一个有 1:1 这个线程的目标。怎么会?例如,有些人想要删除所有换行符,有些人正在剥离。万能支持功能不工作怎么没人有问题?

【问题讨论】:

  • 你问为什么循环打印会有空行? count 的结果是否正确?顺便说一句,您可以在循环之前使用count = len(Lines) 而不是循环中的count += 1https://docs.python.org/3/library/functions.html#print试试print(line,end='')
  • readlines 返回每​​行末尾带有 \n 的行。 print 还添加了一个换行符。考虑改用file1.read().splitlines()

标签: python parsing scripting cross-platform carriage-return


【解决方案1】:

原因是 readlines() 返回按原样读取的行,这意味着返回的列表项也将包括末尾的新行:

>>> import io
>>> io.StringIO('line_1\nline_2').readlines()
['line_1\n', 'line_2']

第二个新行插入默认值为end='\n' 参数print()

【讨论】:

  • 但是如何解决呢?
  • 正如上面其他 cmets 所建议的,只需使用带有 end='' 参数的 print,如下所示:print(line, end='')
猜你喜欢
  • 2021-12-11
  • 2013-03-18
  • 2021-02-13
  • 1970-01-01
  • 2022-01-10
  • 2018-11-11
  • 2016-10-07
  • 1970-01-01
  • 2015-11-19
相关资源
最近更新 更多