Skip to content

Instantly share code, notes, and snippets.

@DanielSzoska
Created October 3, 2012 12:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanielSzoska/3826652 to your computer and use it in GitHub Desktop.
Save DanielSzoska/3826652 to your computer and use it in GitHub Desktop.
preserve type of newlines in textfile while doing something with it
# open textfile
filename = 'text.txt'
with open(filename, 'rU') as f:
lines = f.readlines()
newline = f.newlines
if not newline:
raise IOError, "no newlines in %s, possible no textfile" % filename
if isinstance(newline, tuple):
raise IOError, "more than one type of newlines in %s" % filename
# now do something with lines ...
# save textfile while preserving original newlines
with open('text_processed.txt', 'wb') as f:
f.write(newline.join(lines))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment