Created
March 21, 2013 22:17
-
-
Save dideler/5217307 to your computer and use it in GitHub Desktop.
Playing around with different ways to read file contents into a string.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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', '') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.