SHOW:
|
|
- or go back to the newest paste.
| 1 | - | #1/usr/bin/env python |
| 1 | + | #1/usr/bin/env python |
| 2 | - | |
| 2 | + | |
| 3 | - | # this is from The Python |
| 3 | + | # this is from The Python |
| 4 | - | # Standard Library by example |
| 4 | + | # Standard Library by example |
| 5 | - | # ISBN13: 9780321767349 |
| 5 | + | # ISBN13: 9780321767349 |
| 6 | - | |
| 6 | + | |
| 7 | - | import codecs |
| 7 | + | import codecs |
| 8 | - | import sys |
| 8 | + | import sys |
| 9 | - | |
| 9 | + | |
| 10 | - | encoding = sys.argv[1] |
| 10 | + | encoding = sys.argv[1] |
| 11 | - | filename = encoding + '.txt' |
| 11 | + | filename = encoding + '.txt' |
| 12 | - | |
| 12 | + | |
| 13 | - | print 'Reading from', filename |
| 13 | + | print 'Reading from', filename |
| 14 | - | with codecs.open(filename, mode='rt', encoding=encoding) as f: |
| 14 | + | with codecs.open(filename, mode='rt', encoding=encoding) as f: |
| 15 | - | print repr(f.read()) |
| 15 | + | print repr(f.read()) |
| 16 | ||
| 17 | """ Errors | |
| 18 | ||
| 19 | $ python codecs_open_read.py utf-8 | |
| 20 | Reading from utf-8.txt | |
| 21 | u'pi: \u03c0' | |
| 22 | ||
| 23 | $ python codecs_open_read.py utf-16 | |
| 24 | Reading from utf-16.txt | |
| 25 | Traceback (most recent call last): | |
| 26 | File "codecs_open_read.py", line 14, in <module> | |
| 27 | with codecs.open(filename, mode='rt', encoding=encoding) as f: | |
| 28 | File "/usr/lib/python2.7/codecs.py", line 881, in open | |
| 29 | file = __builtin__.open(filename, mode, buffering) | |
| 30 | IOError: [Errno 2] No such file or directory: 'utf-16.txt' | |
| 31 | ||
| 32 | $ python codecs_open_read.py utf-32 | |
| 33 | Reading from utf-32.txt | |
| 34 | Traceback (most recent call last): | |
| 35 | File "codecs_open_read.py", line 14, in <module> | |
| 36 | with codecs.open(filename, mode='rt', encoding=encoding) as f: | |
| 37 | File "/usr/lib/python2.7/codecs.py", line 881, in open | |
| 38 | file = __builtin__.open(filename, mode, buffering) | |
| 39 | IOError: [Errno 2] No such file or directory: 'utf-32.txt' | |
| 40 | ||
| 41 | """ |