モジュール
自分で作成したモジュールをimportしてみる
ubuntu@ip-172-31-0-101:~$ cat my_module.py
def helloworld():
print("hello world")
>>> import my_module
>>> my_module.helloworld()
hello world
モジュールファイル自身にテストコードを書いた場合、importした時点でそれが実行されちゃう。それを防止するためにif name == "main":
を使うと、importされたときにはそのブロックは実行されない。
ubuntu@ip-172-31-0-101:~$ cat my_module.py
def helloworld():
print("hello world")
if __name__ == "__main__":
helloworld()
ファイル処理
ファイルパスの指定について、OSごとの差異(Linux系は'/'でWindows系は'\'みたいなこと)を考慮する場合はos.path.join
関数を使うとよいとのこと。実際に使ってみる。
>>> import os
>>> os.path.join("usr","local","hoge")
'usr/local/hoge'
>>> os.path.join("/","usr","local","hoge")
'/usr/local/hoge'
ルートディレクトリは含まれないのね。
open関数を使ってファイルを開いてみる。
>>> file = open("file.txt", "w")
>>> file.write("hogehoge\n")
9
>>> file.close()
>>>
ubuntu@ip-172-31-0-101:~$ cat file.txt
hogehoge
pythoneはファイル開いたらクローズしないとだめらしい。開きまくるとこうなる。
ファイルを開くときはクローズを自動処理してくれるwith
を使うと便利。
>>> with open("file.txt", "w") as file:
... file.write("fugafuga\n")
...
9
>>>
ubuntu@ip-172-31-0-101:~$ cat file.txt
fugafuga
かんそう
今日も勉強時間少なめ。業務でAnsible使ったテストツール作成が必要なので明日からはそっちの勉強記事にシフトする予定。