Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

End-line characters from lines read from text file, using Python

Tags:

python

When reading lines from a text file using python, the end-line character often needs to be truncated before processing the text, as in the following example:

f = open("myFile.txt", "r") for line in f:     line = line[:-1]     # do something with line 

Is there an elegant way or idiom for retrieving text lines without the end-line character?

like image 316
pythonquick Avatar asked Dec 04 '08 03:12

pythonquick


People also ask

How do you remove end line breaks from lines read from a text file in Python?

Use the strip() Function to Remove a Newline Character From the String in Python. The strip() function is used to remove both trailing and leading newlines from the string that it is being operated on. It also removes the whitespaces on both sides of the string.

How do you read a line by end of file in Python?

The readline () method reads the text line by line. When it reaches the end of the file, the execution of the while loop stops.

How do I read the last 5 lines of a file in Python?

As we know, Python provides multiple in-built features and modules for handling files. Let's discuss different ways to read last N lines of a file using Python. In this approach, the idea is to use a negative iterator with the readlines() function to read all the lines requested by the user from the end of file.


1 Answers

The idiomatic way to do this in Python is to use rstrip('\n'):

for line in open('myfile.txt'):  # opened in text-mode; all EOLs are converted to '\n'     line = line.rstrip('\n')     process(line) 

Each of the other alternatives has a gotcha:

  • file('...').read().splitlines() has to load the whole file in memory at once.
  • line = line[:-1] will fail if the last line has no EOL.
like image 99
efotinis Avatar answered Oct 02 '22 07:10

efotinis