1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【Python】 ファイル操作について学んだことを備忘録として

Posted at

Pythonのファイル処理

ファイルとファイルオブジェクトについて

  • 組み込み関数open()を使用してファイルを開く(組み込み関数のため特別な宣言などは必要ない)
  • open()関数はファイルオブジェクトで結果を返す
  • open(開くファイル名orファイルパス,モード,エンコード):モードの指定によって、あるパラメータを指定することでファイルをどのように開くかを指定できる
  • 組み込み関数close()を使用してファイルを閉じる(明示的にファイルを閉じない場合、GCによってファイルオブジェクトが削除されたとき自動的に閉じる)
f = open("sample.txt", "r",encoding="utf-8",errors="ignore" )
s = f.read()
print(s)
f.close

ファイルを開くときのモードについて

目的に応じてモードを指定する。
読み込み専用 ⇒ 「r」を使用 
書き出し専用 → 新規作成か? ⇒ Yesなら「w」、Noなら「a」
読み書き両方 → 新規作成か? ⇒ Yesなら「w+」、Noなら開始位置に先頭から読み書きで「r+」(末尾から読み書きなら「a+」)

ファイルに対する操作

  • ファイルに対する操作はファイルオブジェクトに対してメソッドを呼び出す
  • F.read(整数サイズ):文字列として返す。サイズ指定によりバイトサイズを指定できる
  • F.readline(整数サイズ):ファイルから1行の読み込む。文字列として返す。
  • F.readlines(整数サイズ):ファイルから複数行の読み込む。戻り値として文字列を要素として含んだシーケンス(行ごとに分割してリストにする)
  • F.write(文字列):文字列を指定してファイルに書き出しを行う
  • F.writeline(シーケンス):改行文字を追加して書き出せない
python.readメソッド使用
f = open("sample.txt", "r",encoding="utf-8",errors="ignore" )
str_read = f.read()
print(str_read)
# 以下、結果
sample

ad
gv
ewg
g\vewg\v
v
d
vc
dwvc
ds

python.readlineメソッド使用
f = open("sample.txt", "r",encoding="utf-8",errors="ignore" )
str = f.readlines() # 1行ごとを1つ要素としてリストを返す
print(str)
# 以下、結果 
['sample\n', '\n', 'ad\n', 'gv\n', 'ewg\n', 'g\\vewg\\v\n', 'v\n', 'd\n', 'vc\n', 'dwvc\n', 'ds']
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?