5.1 读写文本数据
问题
解决方案
# Read the entire file as a single string
with open('somefile.txt', 'rt') as f:
data = f.read()with open('somefile.txt', 'rt', encoding='latin-1') as f:
...讨论
Last updated
# Read the entire file as a single string
with open('somefile.txt', 'rt') as f:
data = f.read()with open('somefile.txt', 'rt', encoding='latin-1') as f:
...Last updated
# Read with disabled newline translation
with open('somefile.txt', 'rt', newline='') as f:
...>>> # Replace bad chars with Unicode U+fffd replacement char
>>> f = open('sample.txt', 'rt', encoding='ascii', errors='replace')
>>> f.read()
'Spicy Jalape?o!'
>>> # Ignore bad chars entirely
>>> g = open('sample.txt', 'rt', encoding='ascii', errors='ignore')
>>> g.read()
'Spicy Jalapeo!'