What is the Python equivalent of Perl\'s chomp
function, which removes the last character of a string if it is a newline?
An example in Python's documentation simply uses line.strip()
.
Perl's chomp
function removes one linebreak sequence from the end of a string only if it's actually there.
Here is how I plan to do that in Python, if process
is conceptually the function that I need in order to do something useful to each line from this file:
import os
sep_pos = -len(os.linesep)
with open("file.txt") as f:
for line in f:
if line[sep_pos:] == os.linesep:
line = line[:sep_pos]
process(line)