Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert \r text to \n so readlines() works as intended

In Python, you can read a file and load its lines into a list by using

f = open('file.txt','r')
lines = f.readlines()

Each individual line is delimited by \n but if the contents of a line have \r then it is not treated as a new line. I need to convert all \r to \n and get the correct list lines.

If I do .split('\r') inside the lines I'll get lists inside the list.

I thought about opening a file, replace all \r to \n, closing the file and reading it in again and then use the readlines() but this seems wasteful.

How should I implement this?

like image 704
greye Avatar asked Nov 23 '09 18:11

greye


People also ask

What does the readLines () method do?

Definition and Usage The readlines() method returns a list containing each line in the file as a list item. Use the hint parameter to limit the number of lines returned. If the total number of bytes returned exceeds the specified number, no more lines are returned.

Does Python readLines include newline?

In addition to the for loop, Python provides three methods to read data from the input file. The readline method reads one line from the file and returns it as a string. The string returned by readline will contain the newline character at the end.

What does readLines do in R?

readLines() function in R Language reads text lines from an input file. The readLines() function is perfect for text files since it reads the text line by line and creates character objects for each of the lines.

How do you read a new line in a text file in Python?

Method 2: Read a File Line by Line using readline() It will be efficient when reading a large file because instead of fetching all the data in one go, it fetches line by line. readline() returns the next line of the file which contains a newline character in the end.


1 Answers

f = open('file.txt','rU')

This opens the file with Python's universal newline support and \r is treated as an end-of-line.

like image 115
Ned Deily Avatar answered Sep 22 '22 13:09

Ned Deily