forked from dabeaz/python-cookbook
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
30 lines (24 loc) · 1 KB
/
Copy pathexample.py
File metadata and controls
30 lines (24 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# Some examples of reading text files with different options
#
# The file sample.txt is a UTF-8 encoded text file with Windows
# line-endings (\r\n).
# (a) Reading a basic text file (UTF-8 default encoding)
print("Reading a simple text file (UTF-8)")
with open('sample.txt', 'rt') as f:
for line in f:
print(repr(line))
# (b) Reading a text file with universal newlines turned off
print("Reading text file with universal newlines off")
with open('sample.txt', 'rt', newline='') as f:
for line in f:
print(repr(line))
# (c) Reading text file as ASCII with replacement error handling
print("Reading text as ASCII with replacement error handling")
with open('sample.txt', 'rt', encoding='ascii', errors='replace') as f:
for line in f:
print(repr(line))
# (d) Reading text file as ASCII with ignore error handling
print("Reading text as ASCII with ignore error handling")
with open('sample.txt', 'rt', encoding='ascii', errors='ignore') as f:
for line in f:
print(repr(line))