ファイル操作


In [1]:
f = open('todo.txt', encoding='utf-8')

In [2]:
todo_str = f.read()

In [3]:
print(todo_str)


本を書く
新しいPythonライブラリーを試す


In [4]:
f.close()

In [5]:
with open('todo.txt', encoding='utf-8') as f:
    todo_str = f.read()

In [6]:
print(todo_str)


本を書く
新しいPythonライブラリーを試す


In [7]:
f = open('memo.txt', 'w', encoding='utf-8')

In [8]:
f


Out[8]:
<_io.TextIOWrapper name='memo.txt' mode='w' encoding='utf-8'>

In [9]:
f.write('今日は')


Out[9]:
3

In [10]:
f.write('ラーメンが食べたい\n')


Out[10]:
10

In [11]:
f.close()

In [12]:
f = open('memo.txt', 'a', encoding='utf-8')

In [13]:
f.write('夕飯は何にしよう\n')


Out[13]:
9

In [14]:
f.close()

In [15]:
f = open('photo.png', 'rb')

In [16]:
content = f.read()

In [17]:
content[:8]


Out[17]:
b'\x89PNG\r\n\x1a\n'

モジュール


In [18]:
import calc

In [19]:
calc


Out[19]:
<module 'calc' from '/home/hirokiky/dev/pymook-samplecode/2_guide/calc.py'>

In [20]:
calc.add(1, 2)


Out[20]:
3

In [21]:
from calc import add

In [22]:
add(1, 2)


Out[22]:
3

In [23]:
import calc as c

In [24]:
c.add(1, 2)


Out[24]:
3

In [25]:
from calc import add, sub

In [26]:
add(1, 2)


Out[26]:
3

In [27]:
sub(2, 1)


Out[27]:
1

In [28]:
from calc import (
    add,
    sub,
)

標準ライブラリの利用


In [29]:
import re

In [30]:
m = re.search('(P(yth|l)|Z)o[pn]e?', 'Python')

In [31]:
m


Out[31]:
<_sre.SRE_Match object; span=(0, 6), match='Python'>

In [32]:
m[0]


Out[32]:
'Python'

In [33]:
m.group(0)


Out[33]:
'Python'

In [34]:
m = re.search('py(thon)', 'python')

In [35]:
m[0]


Out[35]:
'python'

In [36]:
m[1]


Out[36]:
'thon'

In [37]:
re.search('py', 'ruby')