Pythonのファイルハンドリングとは?
ファイル操作とは、基本的にファイルシステム上のファイルを管理することです。
すべてのオペレーティングシステムは、ファイルを格納するための独自の方法を持っています。
Pythonのファイルハンドリングは、プログラムの中でファイルを操作するのに便利です。
Pythonのファイルハンドリングは、プログラムの中でファイルを扱うのに便利です。
demo_file = open('Demo.txt', 'r')
# This statement will print every line in the filefor x in demo_file:
print (x)
# close the file, very importantdemo_file.close() |
1. open()関数
open()関数は、特定のモードでファイルを開くために使用されます。
基本的にはファイルオブジェクトを作成し、その後の操作に使用します。
構文は以下の様な感じです。
open(file_name, mode)
ファイルを開くためのさまざまなモード
- r: 読み込み
- w: 書き込み
- a: 追加
- r+: 読み出しと書き込み
まず、ファイルを作成し、スクリプトと同じディレクトリに配置する必要があります。
デモ.txt
Welcome to the programming world!
実行ファイル名: Execute_file.py
demo_file = open("Demo.txt", "r")
print(demo_file.read())
demo_file.close() |
結果は以下の通りです。
Welcome to the programming world!
ここでは、Execute_file.py スクリプトが Demo.txt ファイルを開き、全内容を一行ずつ出力しています。
この記事もチェック:Pythonでopenメソッドを使用してファイルを開く方法
2. read()関数
read()関数は、ファイルの内容を読み込むために使用します。
これを実現するには、ファイルを読み込みモードで開く必要があります。
demo_file = open('Demo.txt','w')
demo_file.write("Hello Everyone!.)
demo_file.write("Engineering Discipline.")
demo_file.close() |
結果は以下の通りです。
Welcome to the programming world!
3. write()関数
write()関数は、ファイルへの書き込みや変更を行うために使用されます。
demo_file = open('Demo.txt','a')
demo_file.write(")
demo_file.close() |
結果は以下の通りです。
Demo.txtファイルを開くと、ここに変更が反映されているのがわかる。
Hello Everyone!.
Engineering Discipline.
4. append() function
Fake tag
Output:
Fake code
—FALSE CODE
5. split()関数
split()関数は、ファイル内の行を分割するために使用します。
スクリプト内でスペースに出会うとすぐに分割されます。
デモ.txt
Hello Everyone!.
Engineering Discipline.
Statement added to the end of the file..
Execute_file.py
with open("Demo.txt", "r") as demo_file:
demo_data = demo_file.readlines()
for line in demo_data:
result = line.split()
print(result)
|
結果は以下の通りです。
Hello Everyone!.
Engineering Discipline.
Statement added to the end of the file..
この記事もチェック:Pythonでcopy関数やpopen関数等を使ってファイルをコピーする方法
6. close()関数
close()`関数は、特定のファイルに対する操作の後にそのファイルを閉じるために使用されます。
ファイルに書き込んだ後、close()メソッドを呼ばないと、ファイルに書き込んだすべてのデータがファイルに保存されません。
ファイルへの書き込みが終わったら、リソースを解放するためにファイルをクローズするのは常に良いアイデアです。
構文は以下の様な感じです。
['Hello', 'Everyone!.']
['Engineering', 'Discipline.']
['Statement', 'added', 'to', 'the', 'end', 'of', 'the', 'file..']
7. rename()関数
osモジュールは、特定のファイルの名前を変更するための rename() メソッドを提供します。
構文は以下の通りです。
file-name.close()
8. remove() メソッド
osモジュールは入力として与えられたファイルを削除するために remove() メソッドを提供します。
import os
os.remove('Demo.txt')
|
remove()メソッドを実行する前に…

出力 remove()メソッド実行後

まとめ
以上、今回はPythonのファイル操作について理解しました。