0

According to the official documentation of python, the versions from 3.x and above removed the "U" parameter for reading from a file and included universal support for different carriage returns by default. However this is not working with the latest version (3.8.6).

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

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

I expect an output similar to this:

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

but I get:

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

Why does this happen? According to How can I remove carriage return from a text file with Python? python is now supporting universal newlines. Also: PEP 278 -- Universal Newline Support

So what am I missing? I do not want to strip anything, because that would require me to first figure out, which carriage return gets used by each file. Since this script shall work on every OS, this would be required.

So how do I get this universal support working as intended?

Very strange, I see a lot of topics, very similar to this. But none of those actually have 1:1 the goal of this thread. How comes? Some want to remove all newlines for example, others are stripping. How comes no one has any problem with the universal support feature that is not working?

khelwood
  • 55,782
  • 14
  • 81
  • 108
  • Are you asking why there are blank lines when you print in a loop? Did the `count` come out correct? As an aside, instead of `count += 1` in the loop you couls just use `count = len(Lines)` before the loop. [https://docs.python.org/3/library/functions.html#print](https://docs.python.org/3/library/functions.html#print) Try `print(line,end='')` – wwii Sep 27 '20 at 14:12
  • 2
    `readlines` returns each line with the `\n` at the end. `print` also adds a newline. Consider using `file1.read().splitlines()` instead. – khelwood Sep 27 '20 at 14:14

1 Answers1

1

The reason for this is that readlines() returns the lines read as-is, meaning the list items returned will also include the new lines at the end:

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

The 2nd new line gets inserted with the default value of end='\n' argument of print().

Attila Viniczai
  • 644
  • 2
  • 8