Pythonのファイル操作は、データ処理やシステム管理で欠かせないスキルです。本記事では、ファイルの基本操作から応用テクニックまで幅広く解説します。初心者から実務者まで、誰もが活用できる内容を目指しました。
テキストファイルの読み込み
テキストファイルを読み取る際にはopen()
関数を使います。with
文を併用することで、リソースリークを防ぐことができます。
# ファイルを読み取る基本的な方法
with open("example.txt", "r") as file:
content = file.read()
print(content)
readlines()
を使うと、ファイルを行ごとにリストとして取得できます。
with open("example.txt", "r") as file:
lines = file.readlines()
for line in lines:
print(line.strip())
テキストファイルの書き込み
新しいファイルを作成して内容を書き込むには、モードをw
に設定します。既存のファイルがある場合は上書きされる点に注意してください。
with open("example.txt", "w") as file:
file.write("Hello, World!\n")
file.write("Python is awesome!\n")
ファイルの追記モード
既存のファイルに追記する場合は、モードをa
に設定します。
with open("example.txt", "a") as file:
file.write("This is an appended line.\n")
追記モードはファイルの末尾にデータを追加します。既存のデータは保持されます。
ファイルの存在確認
ファイルが存在するかどうかを確認するには、os.path
モジュールを使用します。
import os
if os.path.exists("example.txt"):
print("File exists.")
else:
print("File does not exist.")
ファイルの削除
ファイルを削除するには、os.remove()
を使用します。
import os
if os.path.exists("example.txt"):
os.remove("example.txt")
print("File deleted.")
else:
print("File does not exist.")
ファイルのリネーム
ファイル名を変更するには、os.rename()
を使います。
import os
os.rename("old_name.txt", "new_name.txt")
バイナリファイルの操作
画像や音声などのバイナリファイルを操作する場合は、モードにb
を追加します。
with open("image.jpg", "rb") as file:
data = file.read()
with open("copy.jpg", "wb") as file:
file.write(data)
CSVファイルの読み込み
CSVファイルの操作にはcsv
モジュールを使用します。
import csv
with open("data.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
CSVファイルの書き込み
CSVファイルにデータを書き込むには、csv.writer()
を使用します。
import csv
with open("data.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", 30, "New York"])
JSONファイルの読み書き
JSONデータを扱うには、json
モジュールを使用します。
import json
# JSONファイルの読み込み
with open("data.json", "r") as file:
data = json.load(file)
print(data)
# JSONファイルへの書き込み
with open("data.json", "w") as file:
json.dump({"name": "Alice", "age": 30}, file)
ディレクトリの作成と削除
ディレクトリを作成するにはos.mkdir()
、削除するにはos.rmdir()
を使用します。
import os
os.mkdir("new_folder")
os.rmdir("new_folder")
複数階層ディレクトリの操作
複数階層のディレクトリを作成・削除する場合は、os.makedirs()
やshutil.rmtree()
を使用します。
import os
import shutil
os.makedirs("parent/child")
shutil.rmtree("parent")
ファイルサイズの取得
ファイルのサイズを取得するには、os.path.getsize()
を使用します。
import os
size = os.path.getsize("example.txt")
print(f"File size: {size} bytes")
ファイルのタイムスタンプ操作
ファイルの作成日時や最終更新日時を取得します。
import os
import time
mtime = os.path.getmtime("example.txt")
print("Last modified:", time.ctime(mtime))
ファイルのコピー
ファイルをコピーするには、shutil.copy()
を使用します。
import shutil
shutil.copy("source.txt", "destination.txt")
ファイルの移動
ファイルを移動するには、shutil.move()
を使用します。
import shutil
shutil.move("source.txt", "new_folder/source.txt")
圧縮ファイルの操作
ZIPファイルを作成・展開するには、zipfile
モジュールを使用します。
import zipfile
# ZIPファイルの作成
with zipfile.ZipFile("archive.zip", "w") as zipf:
zipf.write("example.txt")
# ZIPファイルの展開
with zipfile.ZipFile("archive.zip", "r") as zipf:
zipf.extractall("extracted")
ファイルリストの取得
ディレクトリ内のファイルリストを取得するには、os.listdir()
を使用します。
import os
files = os.listdir(".")
print(files)
安全なファイル操作(with文の使用)
with
文を使用することで、ファイル操作後に自動でリソースが解放されます。
with open("example.txt", "r") as file:
content = file.read()
print(content)
一時ファイルの操作
一時ファイルを作成するには、tempfile
モジュールを使用します。
import tempfile
with tempfile.NamedTemporaryFile(delete=True) as temp:
print(temp.name) # 一時ファイルのパス
temp.write(b"Temporary content")
エラーハンドリング
ファイル操作中のエラーをキャッチするには、try-except
文を使用します。
try:
with open("nonexistent.txt", "r") as file:
content = file.read()
except FileNotFoundError:
print("File not found.")
PDFやExcelファイルの操作
PDFやExcelの操作には、外部ライブラリ(例: PyPDF2
、openpyxl
)を使用します。
# Excelファイルの読み書き例
from openpyxl import Workbook
wb = Workbook()
sheet = wb.active
sheet["A1"] = "Hello"
wb.save("example.xlsx")
まとめ
本記事では、Pythonのファイル操作に関する基本から応用までの幅広いテクニックを解説しました。テキストファイルの読み書きや追記モード、CSVやJSONファイルの扱い方から、ディレクトリ操作、ファイルのコピーや移動、圧縮ファイルの操作まで、実務で頻繁に活用されるスキルを網羅しました。
これらのテクニックを使いこなせば、データ処理やシステム管理での作業効率が大幅に向上します。また、安全なファイル操作やエラーハンドリングを徹底することで、ミスを防ぎ、信頼性の高いコードを書くことができます。
Pythonの強力なファイル操作機能を活用して、柔軟かつ効率的なプログラムを作成してください!
コメント