file = open('example_text.txt', 'r')
print(type(file), '\n')
contents = file.read()
print(contents)
file.close()
<class '_io.TextIOWrapper'> First line of text Second line of text Third line of text
# менеджер контекста
with open('example_text.txt', 'r') as file:
contents = file.read()
print(contents)
First line of text Second line of text Third line of text
import os
os.getcwd()
'/Users/dm_fedorov'
with open('data_files/test_file.txt', 'r') as file:
contents = file.read(500)
part_2 = file.read(24)
print('1:', contents)
print('2:', part_2)
1: Александр Пушкин — Осень. I Октябрь уж наступил — уж роща отряхает Последние листы с нагих своих ветвей; Дохнул осенний хлад — дорога промерзает. Журча еще бежит за мельницу ручей, Но пруд уже застыл; сосед мой поспешает В отъезжие поля с охотою своей, И страждут озими от бешеной забавы, И будит лай собак уснувшие дубравы. II Теперь моя пора: я не люблю весны; Скучна мне оттепель; вонь, грязь — весной я болен; Кровь бродит; чувства, ум тоскою стеснены. Суровою зимой я более доволен, Люблю ее сне 2: га; в присутствии луны К
with open('example_text.txt') as file:
lines = file.readlines()
print(lines)
['First line of text\n', 'Second line of text\n', 'Third line of text']
with open('plan.txt') as file:
planets = file.readlines()
print(planets, '\n')
for planet in reversed(planets):
print(planet.strip())
['Mercury\n', 'Venus\n', 'Earth\n', 'Mars\n', 'Jupiter\n', 'Saturn\n', 'Uranus\n', 'Neptune\n'] Neptune Uranus Saturn Jupiter Mars Earth Venus Mercury
with open('plan.txt') as file:
for line in file:
print(len(line.strip()))
7 5 5 4 7 6 6 7
with open("top.txt", 'w') as output_file:
output_file.write("Hello!\n")
print("this is string example....wow!!!")
print("th1s 1s str1ng xampl....wow!!!")
this is string example....wow!!! th1s 1s str1ng xampl....wow!!!
trantab = str.maketrans({'i': '1', 'e': None})
print(trantab)
s = "this is string example....wow!!!"
print(s.translate(trantab))
intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)
print(trantab)
s = "this is string example....wow!!!"
print(s.translate(trantab))
{97: 49, 101: 50, 105: 51, 111: 52, 117: 53} th3s 3s str3ng 2x1mpl2....w4w!!!
trantab = str.maketrans("", "", "sw")
print(trantab)
s = "this is string example....wow!!!"
print(s.translate(trantab))
{115: None, 119: None} thi i tring example....o!!!
Документация про кодировки: https://ancatmara.gitbooks.io/digital-literacy/content/seminar-2.html
# про unicode: https://djbook.ru/examples/24/
# указывайте кодировку по умолчанию!
with open("top_cp1251.txt", 'w', encoding='cp1251') as output_file:
output_file.write("Привет, мир!\n")
with open("top_cp1251.txt") as output_file:
print(output_file.read())
--------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) <ipython-input-24-c88167f7bee7> in <module> 1 with open("top_cp1251.txt") as output_file: ----> 2 print(output_file.read()) ~/anaconda3/lib/python3.7/codecs.py in decode(self, input, final) 320 # decode input (taking the buffer into account) 321 data = self.buffer + input --> 322 (result, consumed) = self._buffer_decode(data, self.errors, final) 323 # keep undecoded input until the next call 324 self.buffer = data[consumed:] UnicodeDecodeError: 'utf-8' codec can't decode byte 0xcf in position 0: invalid continuation byte
'\N{GRINNING FACE}'
'😀'
'\U0001f600'
'😀'
'\N{SUPERSCRIPT TWO}'
'²'
'привет'.encode(encoding='utf-8')
b'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82'
'hello'.encode(encoding='utf-8')
b'hello'
'привет'.encode(encoding='cp1251')
b'\xef\xf0\xe8\xe2\xe5\xf2'
b'\xef\xf0\xe8\xe2\xe5\xf2'.decode(encoding='utf-8')
--------------------------------------------------------------------------- UnicodeDecodeError Traceback (most recent call last) <ipython-input-31-3b6a75102fa4> in <module> ----> 1 b'\xef\xf0\xe8\xe2\xe5\xf2'.decode(encoding='utf-8') UnicodeDecodeError: 'utf-8' codec can't decode byte 0xef in position 0: invalid continuation byte
b'\xef\xf0\xe8\xe2\xe5\xf2'.decode(encoding='cp1251')
'привет'
with open("top_cp1251.txt", 'r', encoding='cp1251') as output_file:
print(output_file.read())
Привет, мир!