with open('somefile.txt', 'rt') as f: data = f.read()
with open('somefile.txt', 'rt') as f: for line in f: # process line ...
with open('somefile.txt', 'wt') as f: f.write(text1) f.write(text2) ...
with open('somefile.txt', 'wt') as f: print(line1, file=f) print(line2, file=f) ...
with open('somefile.txt', 'rt', encoding='latin-1') as f:
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!'