Skip to content

Instantly share code, notes, and snippets.

@dideler
Created March 21, 2013 22:17
Show Gist options
  • Save dideler/5217307 to your computer and use it in GitHub Desktop.
Save dideler/5217307 to your computer and use it in GitHub Desktop.
Playing around with different ways to read file contents into a string.
#!/usr/bin/env python
import sys
filename = sys.argv[1]
# These do not remove \n
with open(filename) as f:
s = ''.join(f.readlines())
with open(filename) as f:
s = ''.join(f)
with open(filename) as f:
s = f.read() # Fastest according to my tests.
# These remove \n
with open(filename) as f:
s = ' '.join(line.replace('\n', '') for line in f)
with open(filename) as f:
s = ' '.join(line.rstrip() for line in f)
with open(filename) as f:
s = f.read().replace('\n', '')
@dideler
Copy link
Author

dideler commented Mar 21, 2013

This is not an exhaustive list. If you think there is a good one missing from the list, leave it as a comment and I'll add it.

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