2018年9月9日日曜日

【Python3】pythonの教科書(5) ~モジュール、ファイル読み書き

1、モジュール
(1)モジュールを取り込む
ファイル名がモジュール名となります。
モジュールを取り込む場合は、importを使います。
import モジュール名
hoge.pyというファイルを作った場合は、import hogeで取り込むことができます。

異なるパスにモジュールを配置した場合は、「ディレクトリの区切り」は"."で表します

(2) 標準モジュール
以下URLで確認できます。
https://docs.python.jp/3/py-modindex.html

(3)パッケージ管理ツール「pip」
パッケージ一覧登録「PyPI」(https://pypi.org/)は
 pip install パッケージ名
でインストールできます。
※pip uninstall パッケージ名、で削除できます
※インストールしたパッケージは、「c:\Users\ユーザ名\AppData\Local\Programs\Python\Python37-32(Pythonのバージョン名)\Lib\site-packages」に保存されます


2、ファイルの読み書き
①ファイルを開く open()
②ファイルを読み書きする read()/write()
③ファイルを閉じる close()

(1) ファイルの読込
test.txtファイルを読み込む例です。

a_file = open("test.txt", encoding="utf-8")
# 日本語読込の場合は、a_file = open("mt7_7_sjis.txt", encoding="sjis")
s = a_file.read()
a_file.close()


【ファイルを1行づつ読み込む場合】
また、with構文を使うと、close文を使わなくっても、自動的に処理の最後にclose文を実行してくれます。

key = "test"
with open("test.txt", encoding="utf-8") as tf:
    for i, line in enumerate(tf):
        # 文字列 key が行に含まれるか?
        if line.find(key) >= 0:
            print(i+1, ":", line)

(2) ファイルの書込
try-catchを使って、 test.txtファイルを書き込む例です。

a_file = open("test.txt", mode="w", encoding="utf-8")
try:
  a_file.write("test=\n今日は晴れです\n")
finally:

  a_file.close()

with構文を使って、ファイル書き込みを行います。

with open("test.txt", mode="w", encoding="utf-8") as f:
    f.write("test=\n今日は晴れです")


 (3) jsonファイルの読込/書込
import jsonを使用します。
①読込例
import json
filename = "test.json"
with open(filename, "r") as fp:
    r = json.load(fp)
    print("no=", r["no"])
    print("code=", r["code"])
    print("scr=", r["scr"])


②書込例
import json
# 辞書型のデータ(数値、タプル、文字列が使えます)
data = {
  "no": 1,
  "code": ("num", 1, 10),
  "scr": "test,test......",

filename = "test.json"
#オブジェクトをJSON文字列に変換
with open(filename, "w") as fp:
    json.dump(data, fp)

0 件のコメント:

コメントを投稿