Skip to content

Instantly share code, notes, and snippets.

@seanh
Created August 25, 2010 16:56
Show Gist options
  • Select an option

  • Save seanh/549851 to your computer and use it in GitHub Desktop.

Select an option

Save seanh/549851 to your computer and use it in GitHub Desktop.
text = open('unknownEndings.txt','rU').read()
open('localEndings.txt','w').write(content)
lines = open('unknownEndings.txt','rU').readlines()
open('localEndings.txt','w').writelines(lines)
@seanh
Copy link
Copy Markdown
Author

seanh commented Aug 25, 2010

To convert a file with any type of newlines to the local system's newlines read the file in rU mode then write it in w mode.


Different operating systems use different escape sequences for newlines (e.g. \n, \r, \r\n...).

Python uses \n's for newlines internally, but when writing a file in text mode (w not wb) on Windows it converts \n's to Windows newlines. If the text that you pass to write() or writelines() contains Windows newlines (or some newlines other than \n's), maybe because you read that text from a file that contains those newlines, these will not be converted to the local system's newlines when you write to file.

If you read a file in universal mode (rU instead of r) then Python will convert all sorts of newlines to \n's. Therefore, you can convert a file to the local system's newlines format by reading the file in rU mode and then writing it in w mode.

Also see: http://docs.python.org/release/2.6.5/library/functions.html#open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment