Python3のファイルの操作方法を紹介します。
やりたいこと
- ファイルの書き込みと読み取り
- フォルダ内のファイル一覧
- ファイル名の変更
- ファイルが存在しているかの確認
ファイルの書き込みと読み取り
open
関数でファイルの書き込みと読み取りを実現できます。
open("file_name", "mode")
上記の記述で、ファイルにアクセスします。
mode
の部分、
'r' : read。閲覧モード。
'w' : write。編集モード。
'a' : append。ファイルの末尾に内容を追加するモード。
'r+' : read + write。閲覧と編集モード。
Write
file = open('/path_to_file/file_name', 'r')
file.write("新規のファイルです。")
file.write("新しい内容を追加します。")
file.write("ここは三行目です。")
file.close()
with
を利用する場合、処理終了後に自動的にファイルを閉じるので、手動でclose()の必要はなくなります。
with open('/path_to_file/file_name', 'w') as file:
file.write("新規のファイルです。")
file.write("新しい内容を追加します。")
file.write("ここは三行目です。")
Read
file = open('/path_to_file/file_name', 'r')
# ファイルの内容を出力する
print(file.read())
# ファイルの5番目文字までの内容を出力する
print(file.read(5))
# ファイルの1行目までの内容を出力する
print(file.readline())
# ファイルの1行目の3番目文字まで内容を出力する
print(file.readline(3))
# ファイルの一行ずつの内容を配列で出力する
print(file.readlines())
# > ['新規のファイルです。', '新しい内容を追加します。', 'ここは三行目です。']
ファイル一覧
os
やglob
のモジュールを使えば、ファイル一覧の取得はできます。
osモジュール
import os
list = os.listdir("path")
print(list)
globモジュール
import glob
files = glob.glob('path/*.txt')
print(files)
glob では、ファイルの形式の指定はできます。
ファイル名の変更
os
モジュールでファイル名の変更はできます。
import os
# os.rename('/path/original_file_name.type', '/path/new_file_name.type')
os.rename('/tmp/user.txt', '/tmp/customer.txt')
ファイルが存在しているかの確認
open
関数やos
モジュール、どちらでも確認できます。
open関数
try:
with open('file_name') as f:
print(f.readlines())
except IOError
print("ファイルにアクセスできません")
osモジュール
os.pathでパスが存在しているか、ファイルか、フォルダーかの確認ができます。
- os.path.exists(path) : true/falseの結果を返す
- os.path.isfile(path) : true/falseの結果を返す
- os.path.isdir(path) : true/falseの結果を返す
import os
os.path.exist('/path/of/file')
ファイル関連の紹介は以上です。