カネキン伊藤テック

ファイル操作

ファイルから読み込む

# 第二引数はモード, rは読み込みモードを意味する
# 標準ではエンコーディングUTF-8で文字列として読み込む
with open("hoge.txt", "r") as fh:
    all_content_in_string = fh.read()
    # all_content_in_string は str 型

# encodingで解釈する文字コードを変更することもできる
with open("hoge.txt", encoding="cp932") as fh:
    content = fh.read()  # CP932で解釈された文字列

# 第二引数を省略すると "r"を指定したのと同じ
with open("hoge.txt", "r") as fh:
    all_content_in_string = fh.read()

# with構文を使わない場合: 自分で明示的にclose
fh = open("hoge.txt")
all_content_in_string = fh.read()
fh.close()

# 文字数指定で読み込む
with open("hoge.txt", "r") as fh:
    first_4chars = fh.read(4)
    # read(N)で空文字列が返ってきた場合終わりに到達している

# バイナリで読み込む場合はモードに b を付け足す
with open("hoge.bin", "rb") as fh:
    all_content_in_binary = fh.read()
    # all_content_in_binary は bytes 型

# バイナリモードでバイト数を指定して読み込む
with open("hoge.bin", "rb") as fh:
    first_4bytes = fh.read(4)
    # b'' が返ってきた場合終わりに到達している

encoding には以下のようなエンコーディングが指定できる(他にもある)

  • utf-8 / utf8
  • utf16 / utf-16
  • cp932 (WindowsのShift JIS)
  • sjis
  • iso-2022-jp いわゆるJIS
  • euc_jp

ファイルから1行ずつ読み込む

with open("hoge.txt") as fh:
    for line in fh:
	print(line)  # lineは最後に改行が入っている

# 一気にlistとして読み込むこともできる
with open("hoge.txt") as fh:
    lines = list(fh)

open() で得られるファイルオブジェクト(テキストモード)は行を順番に返すイテレータを実装している。

ファイルに書き込む(write)

# "w" モードでオープンすると存在してない場合新規作成,
# 存在している場合ファイルは空になる
# テキストモードでは文字列はデフォルトでUTF-8エンコーディングで
# バイト列に変換され書き込まれる
with open("hoge.txt", "w") as fh:
    fh.write("もじ")
    fh.write("さらに文字")

# "a" モードでオープンすることでファイルの末尾に追加して書き込める
with open("hoge.txt", "a") as fh:
    fh.write("追記します")

# エンコーディングを指定してUTF-8ではないエンコーディングで文字列を
# 書き込むこともできる
with open("hoge.txt", "w", encoding="cp932") as fh:
    fh.write("これはcp932文字列として保存される")

# bをモードに付け加えるとバイナリモードでオープン
# bytes型をwriteで書き込む
with open("hoge.txt", "wb") as fh:
    fh.write(b'binary_data')

ファイルの存在を確認する(os.path.exists)

標準ライブラリ os.path の関数 os.path.exists() を使う。標準なので何かをインストールせずともimportできる。

import os.path
target_file = "./target_file.txt"
if os.path.exists(target_file):
    print("ある")
else:
    print("ない")

ファイルを削除する(os.remove)

標準ライブラリ os の関数 os.remove() を使う。標準なので何かをインストールせずともimportできる。
指定されたファイルが存在しない場合例外 OSError が発生する。

import os
target_file = "./target_file.txt"
os.remove(target_file)

ファイルの名前を変更する(os.rename)

os.rename() が使える。

import os
source_file = "./hoge.txt"
new_name = "./hoge_new_name.txt"
os.rename(source_file, new_name)

ディレクトリを再帰的に削除する

標準ライブラリ shutil にある関数 shutil.rmtree() を使う。標準なので何かをインストールせずともimportできる。

ディレクトリに入っているものも含め丸ごと削除される。

import shutil
path = "./target_dir"
shutil.rmtree(path)

パス要素をプラットフォーム問わず安全につなげる(os.path.join)

os.path.join() が使える。

パスの区切り文字はWindowsだと \ でUNIX系/Linuxだと / だったりするのでマルチプラットフォームでちゃんと動作させたいプログラムやライブラリなどはこういった方法でパスを操作したほうがよさそうだ。

import os.path
dir_name = "my_dir"
file_name = "file_name.txt"
os.path.join(dir_name, file_name)

Windows系とUNIX/Linux系ではパスの区切り文字が違うのでこのようにしたほうがポータブルな実装になる。

実行中のPythonファイルが存在しているディレクトリの絶対パスを得る(os.path.abspath)

os.path.abspath()os.path.dirname()__file__ を組み合わせて取得できる。

import os.path
os.path.dirname(os.path.abspath(__file__))

パスからファイル名部分だけを取り出す(os.path.basename)

os.path.basename() でできる。

import os.path
path = "/path/to/hoge.txt"
file_part = os.path.basename(path)
#=> "hoge.txt" を得る

パスからディレクトリ名部分だけを取り出す(os.path.dirname)

os.path.dirname() でできる。絶対パスでも相対パスでもok。

import os.path
path = "/path/to/hoge.txt"
dir_part = os.path.dirname(path)
#=> "/path/to" を得る

パスがファイルであるかどうかを調べる(os.path.isfile)

os.path.isfile() でできる。

import os.path
target_path = "something.txt"
is_file = os.path.isfile(target_path)  # bool

パスがディレクトリであるかどうかを調べる(os.path.isdir)

os.path.isdir() でできる。

import os.path
target_path = "some_dir/"
is_dir = os.path.isdir(target_path)  # bool

ディレクトリの中のファイルリストを取得(os.listdir)

os.listdir() でできる。

import os
dir_name = "./my_dir"

# os.listdir で取得する
files = os.listdir(dir_name)

# 再帰的に全部の内容を取得する関数
def list_files_recursive(d):
    import os.path
    ret_files = []
    for f in os.listdir(d):
        path = os.path.join(d, f)
        if os.path.isdir(path):
            ret_files.extend(list_files_recursive(path))
        else:
            ret_files.append(path)
    return ret_files

参考リンク