Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iterating through files with carriage returns

Tags:

python

Is there a way to iterate through a text file using the syntax,

with open(filename,'r') as f:
  for line in f:
    print f

if the file only contains carriage returns and no newline characters?

So far all I can do is

with open(filename,'r') as f:
  for line in f.read().split('\r'):
    print f

But the files are sometimes huge. I don't want to modify the file using dos2unix because another software program needs it in the original format.

like image 818
hatmatrix Avatar asked Mar 02 '11 22:03

hatmatrix


1 Answers

You can use Python's universal newline support for open()

In addition to the standard fopen() values mode may be 'U' or 'rU'. Python is usually built with universal newline support; supplying 'U' opens the file as a text file, but lines may be terminated by any of the following: the Unix end-of-line convention '\n', the Macintosh convention '\r', or the Windows convention '\r\n'. All of these external representations are seen as '\n' by the Python program. If Python is built without universal newline support a mode with 'U' is the same as normal text mode. Note that file objects so opened also have an attribute called newlines which has a value of None (if no newlines have yet been seen), '\n', '\r', '\r\n', or a tuple containing all the newline types seen.

like image 147
Daniel DiPaolo Avatar answered Sep 30 '22 14:09

Daniel DiPaolo