Python ファイルの作成、読み込み、書き込み、削除について
ファイル操作
「Pythonによるあたらしいデータ分析の教科書」とhttps://qiita.com/hrsma2i/items/583ed431c14fc9140f72、https://www.javadrive.jp/python/file/index9.htmlを参照。
まず
import os
でosモジュールをimportしておく。
・ファイルの書き込みとファイルが閉じているか確認する。
with open ('sample.txt','w',encoding='utf-8') as f: #'w'でファイルが無くても自動で作る。with openでファイルが自動で閉じる。 f.write('あいうえお') #sample.txtにあいうえおと書き込む。 print(f.closed) #ファイルが閉じていたらTrue。
・ファイルの読み込み
with open ('sample.txt',encoding='utf-8') as f: data=f.read() print(data) #sample.txtに書き込んだ「あいうえお」を出力。
・ファイルの削除、削除前のディレクトリになにがあるか確認する。
file_name=[f.name for f in os.scandir()] #リスト内包表記。os.scndir()はコマンドのlsと同じ意味。 print(file_name)
・削除後
os.remove('sample.txt') #sample.txtを削除 file_name=[f.name for f in os.scandir()] print(file_name)
実際にsample.txtが消えていることが分かる。