Pythonファイル操作入門|テキストファイルの読み書き
Python初心者向けにファイル操作の基本を解説。テキストファイルの読み書きから例外処理まで、安全なファイル操作方法を実例とともに学べます。
Pythonファイル操作入門|テキストファイルの読み書き
みなさん、Pythonでプログラムを作っていて「作ったデータをファイルに保存したい」と思ったことはありませんか?
「設定を外部ファイルから読み込みたい」 「ログを記録しておきたい」 「計算結果をファイルに出力したい」
こんな時に必要になるのがファイル操作です。
でも大丈夫です!Pythonのファイル操作はとてもシンプルで、初心者の方でも簡単に覚えることができます。 一度マスターしてしまえば、プログラムの実用性が格段に向上しますよ。
この記事では、Python初心者の方に向けて、テキストファイルの読み書きの基本から安全な操作方法まで、わかりやすく解説します。 読み終わる頃には、自信を持ってファイル操作ができるようになるはずです!
ファイル操作って何?なぜ必要なの?
まずは、ファイル操作の基本的な考え方を理解しましょう。 これがわかると、なぜファイル操作が重要なのかがスッキリ理解できます。
プログラムとファイルの関係
普通にプログラムを書いて実行すると、データはメモリ上にあります。 でも、プログラムが終了するとメモリ上のデータは消えてしまいます。
ファイル操作を使うと、データを永続的に保存できるんです。
例えば、こんなことができるようになります。
# ユーザー設定をファイルに保存する例def save_user_settings(username, theme, language): """ユーザー設定をファイルに保存""" settings_text = f"""ユーザー名: {username}テーマ: {theme}言語: {language}保存日時: 2024-07-07""" with open('user_settings.txt', 'w', encoding='utf-8') as file: file.write(settings_text) print(f"{username}さんの設定を保存しました!")
# 使用例save_user_settings("太郎", "ダーク", "日本語")
このように、プログラムを終了しても設定が残るので、次回起動時に読み込むことができます。
ファイル操作で何ができる?
ファイル操作を覚えると、こんなことができるようになります。
設定データの管理 ユーザーの好みや設定をファイルに保存して、プログラム起動時に読み込めます。
ログの記録 プログラムの動作履歴をファイルに記録して、後で確認できます。
データの保存 計算結果やユーザーが入力したデータを保存できます。
レポートの生成 処理結果をわかりやすいレポート形式でファイルに出力できます。
他のプログラムとの連携 他のプログラムが作ったファイルを読み込んだり、他のプログラムが読めるファイルを作ったりできます。
Pythonのファイル操作の特徴
Pythonのファイル操作は、とてもシンプルで直感的です。
基本的な流れはこんな感じです。
- ファイルを開く
- ファイルに書き込む(または読み込む)
- ファイルを閉じる
でも、手動でファイルを閉じるのを忘れちゃうことがあります。
そこで、Pythonには**with
文**という便利な機能があります。
# with文を使った安全なファイル操作with open('sample.txt', 'w', encoding='utf-8') as file: file.write('Hello, Python!')# ここで自動的にファイルが閉じられる
print("ファイルに書き込み完了!")
with
文を使うと、自動的にファイルが閉じられるので安全です。
これから紹介する例では、このwith
文を使って説明していきますね。
ファイルを読み込んでみよう
それでは、実際にファイルを読み込む方法を学びましょう。 まずは基本的な読み込み方法から始めます。
基本的な読み込み方法
ファイルを読み込む方法は、主に3つあります。 それぞれの特徴を理解して、目的に応じて使い分けましょう。
まず、練習用のファイルを作ってみます。
# 練習用ファイルの作成sample_text = """第1行: Pythonは楽しい!第2行: ファイル操作を学習中第3行: どんどん上達しています第4行: 実践的な例を試そう第5行: きっとできるようになる"""
with open('practice.txt', 'w', encoding='utf-8') as file: file.write(sample_text)
print("練習用ファイルを作成しました")
方法1:ファイル全体を一度に読み込む
def read_whole_file(): """ファイル全体を一度に読み込む方法""" with open('practice.txt', 'r', encoding='utf-8') as file: content = file.read() return content
# 実行してみようwhole_content = read_whole_file()print("=== ファイル全体の内容 ===")print(whole_content)
方法2:行ごとのリストとして読み込む
def read_as_lines(): """行ごとのリストとして読み込む方法""" with open('practice.txt', 'r', encoding='utf-8') as file: lines = file.readlines() return lines
# 実行してみようlines_list = read_as_lines()print("=== 行ごとのリスト ===")for i, line in enumerate(lines_list): print(f"行{i+1}: {line.strip()}") # strip()で改行文字を除去
方法3:1行ずつ順番に読み込む
def read_line_by_line(): """1行ずつ順番に読み込む方法""" lines = [] with open('practice.txt', 'r', encoding='utf-8') as file: for line in file: lines.append(line.strip()) return lines
# 実行してみようprocessed_lines = read_line_by_line()print("=== 1行ずつ処理した結果 ===")for i, line in enumerate(processed_lines): print(f"{i+1}. {line}")
どの方法も同じファイルを読み込んでいますが、データの形が少し違います。 小さなファイルなら方法1が簡単ですが、大きなファイルの場合は方法3がメモリ効率的です。
大きなファイルを効率的に読み込む
大きなファイルを扱う時は、メモリ使用量に注意が必要です。 ファイル全体をメモリに読み込むと、コンピュータの動作が重くなってしまうことがあります。
そんな時は、少しずつ読み込む方法を使いましょう。
# 大きなファイルのサンプル作成def create_large_file(): """練習用の大きなファイルを作成""" with open('large_file.txt', 'w', encoding='utf-8') as file: for i in range(1000): file.write(f"行番号{i+1}: これは大きなファイルのサンプルです。") print("大きなファイルを作成しました")
create_large_file()
# 効率的な読み込み方法def read_large_file_safely(filename): """メモリ効率を考えた読み込み""" line_count = 0 with open(filename, 'r', encoding='utf-8') as file: for line in file: line_count += 1 # 100行ごとに進捗を表示 if line_count % 100 == 0: print(f"処理中... {line_count}行完了") return line_count
# 実行してみようtotal_lines = read_large_file_safely('large_file.txt')print(f"ファイル全体で{total_lines}行でした")
特定の条件で検索
大きなファイルから特定の内容を探したい時は、こんな方法が便利です。
def search_in_file(filename, search_word): """ファイルから特定の文字列を検索""" matches = [] with open(filename, 'r', encoding='utf-8') as file: for line_number, line in enumerate(file, 1): if search_word in line: matches.append({ 'line_number': line_number, 'content': line.strip() }) return matches
# 「行番号100」を含む行を検索search_results = search_in_file('large_file.txt', '行番号100')print("=== 検索結果 ===")for result in search_results: print(f"行{result['line_number']}: {result['content']}")
このように、大きなファイルでも効率的に処理できます。
ファイルに書き込んでみよう
次は、ファイルにデータを書き込む方法を学びましょう。 書き込み方法によって、ファイルの扱われ方が変わるので注意が必要です。
基本的な書き込み方法
ファイルの書き込みには、主に2つのモードがあります。
'w'モード:新規作成または上書き
def write_new_file(): """新しいファイルを作成(または上書き)""" shopping_list = [ "牛乳", "パン", "卵", "りんご", "チーズ" ] with open('shopping_list.txt', 'w', encoding='utf-8') as file: file.write("今日の買い物リスト") file.write("=" * 20 + "") for i, item in enumerate(shopping_list, 1): file.write(f"{i}. {item}") print("買い物リストを作成しました")
write_new_file()
'a'モード:既存ファイルに追記
def add_to_shopping_list(): """買い物リストに商品を追加""" additional_items = [ "バナナ", "ヨーグルト", "サラダ" ] with open('shopping_list.txt', 'a', encoding='utf-8') as file: file.write("追加の商品:") for i, item in enumerate(additional_items, 6): file.write(f"{i}. {item}") print("買い物リストに商品を追加しました")
add_to_shopping_list()
# ファイルの内容を確認def show_file_content(filename): """ファイルの内容を表示""" print(f"=== {filename} の内容 ===") with open(filename, 'r', encoding='utf-8') as file: content = file.read() print(content)
show_file_content('shopping_list.txt')
いろんな形式でデータを書き込む
実際のプログラムでは、様々な形式でデータを保存することがあります。 いくつかのパターンを見てみましょう。
CSVのような形式で保存
def save_student_scores(): """学生の成績をCSV形式で保存""" students = [ {"name": "田中太郎", "math": 85, "english": 78, "science": 92}, {"name": "佐藤花子", "math": 92, "english": 88, "science": 85}, {"name": "鈴木一郎", "math": 78, "english": 90, "science": 83}, {"name": "高橋美咲", "math": 88, "english": 85, "science": 90} ] with open('student_scores.csv', 'w', encoding='utf-8') as file: # ヘッダー行 file.write("名前,数学,英語,理科") # データ行 for student in students: file.write(f"{student['name']},{student['math']},{student['english']},{student['science']}") print("学生の成績を保存しました")
save_student_scores()
レポート形式で保存
def create_monthly_report(): """月次レポートを作成""" sales_data = { "1月": {"売上": 150000, "件数": 45}, "2月": {"売上": 180000, "件数": 52}, "3月": {"売上": 165000, "件数": 48} } with open('monthly_report.txt', 'w', encoding='utf-8') as file: file.write("月次売上レポート") file.write("=" * 30 + "
") total_sales = 0 total_count = 0 for month, data in sales_data.items(): sales = data["売上"] count = data["件数"] average = sales / count file.write(f"{month}の実績:") file.write(f" 売上金額: {sales:,}円") file.write(f" 取引件数: {count}件") file.write(f" 平均単価: {average:,.0f}円
") total_sales += sales total_count += count # 合計 file.write("-" * 30 + "") file.write(f"合計売上: {total_sales:,}円") file.write(f"合計件数: {total_count}件") file.write(f"全体平均: {total_sales/total_count:,.0f}円") print("月次レポートを作成しました")
create_monthly_report()show_file_content('monthly_report.txt')
ログファイルの作成
def create_log_file(): """ログファイルを作成""" import datetime log_events = [ ("INFO", "プログラム開始"), ("DEBUG", "設定ファイル読み込み"), ("WARNING", "メモリ使用量が多いです"), ("ERROR", "ファイルが見つかりません"), ("INFO", "プログラム終了") ] with open('program.log', 'w', encoding='utf-8') as file: for level, message in log_events: # 現在時刻を取得(サンプルなので固定値) timestamp = "2024-07-07 10:30:00" file.write(f"[{timestamp}] {level}: {message}") print("ログファイルを作成しました")
create_log_file()show_file_content('program.log')
このように、目的に応じて様々な形式でファイルを作成できます。
エラーに備えよう!安全なファイル操作
ファイル操作では、様々なエラーが発生する可能性があります。 エラーが起きても慌てずに対処できるように、安全な操作方法を覚えましょう。
よくあるエラーと対処法
ファイルが見つからない場合
def safe_file_read(filename): """安全なファイル読み込み""" try: with open(filename, 'r', encoding='utf-8') as file: content = file.read() return {"success": True, "content": content} except FileNotFoundError: return { "success": False, "error": f"ファイル '{filename}' が見つかりません" } except Exception as e: return { "success": False, "error": f"予期しないエラー: {e}" }
# 使用例result = safe_file_read("存在しないファイル.txt")if result["success"]: print(f"ファイル内容: {result['content']}")else: print(f"エラー: {result['error']}")
# 存在するファイルでテストresult = safe_file_read("shopping_list.txt")if result["success"]: print("ファイルの読み込みに成功しました")else: print(f"エラー: {result['error']}")
書き込み権限がない場合
def safe_file_write(filename, content): """安全なファイル書き込み""" try: with open(filename, 'w', encoding='utf-8') as file: file.write(content) return {"success": True, "message": f"'{filename}' に書き込み完了"} except PermissionError: return { "success": False, "error": "ファイルへの書き込み権限がありません" } except Exception as e: return { "success": False, "error": f"書き込みエラー: {e}" }
# 使用例test_content = "これはテストファイルです。"result = safe_file_write("test_file.txt", test_content)
if result["success"]: print(result["message"])else: print(f"エラー: {result['error']}")
ファイルの存在確認
ファイル操作を行う前に、ファイルが存在するかチェックすることも大切です。
import os
def check_file_info(filename): """ファイルの情報をチェック""" print(f"=== {filename} の情報 ===") # ファイルの存在確認 if os.path.exists(filename): print("✅ ファイルが存在します") # ファイルサイズを確認 file_size = os.path.getsize(filename) print(f"📄 ファイルサイズ: {file_size} バイト") # ファイルの内容を少し表示 try: with open(filename, 'r', encoding='utf-8') as file: first_line = file.readline().strip() print(f"📝 最初の行: {first_line}") except Exception as e: print(f"❌ 読み込みエラー: {e}") else: print("❌ ファイルが存在しません")
# 作成したファイルをチェックcheck_file_info("shopping_list.txt")check_file_info("存在しないファイル.txt")
バックアップ機能付きの書き込み
重要なファイルを更新する時は、バックアップを作成しておくと安心です。
import shutilimport datetime
def backup_and_write(filename, new_content): """バックアップを作成してからファイルを更新""" # 既存ファイルがある場合はバックアップ作成 if os.path.exists(filename): # バックアップファイル名を作成 timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") backup_filename = f"{filename}.backup_{timestamp}" try: # ファイルをコピー shutil.copy2(filename, backup_filename) print(f"✅ バックアップ作成: {backup_filename}") except Exception as e: print(f"❌ バックアップ作成失敗: {e}") return False # 新しい内容を書き込み result = safe_file_write(filename, new_content) if result["success"]: print(f"✅ ファイル更新完了: {filename}") return True else: print(f"❌ ファイル更新失敗: {result['error']}") return False
# 使用例updated_content = """更新された買い物リスト========================1. 牛乳2. パン3. 卵4. 新商品:アイスクリーム5. 新商品:お菓子"""
backup_and_write("shopping_list.txt", updated_content)
このように、エラーハンドリングを組み込むことで、安全で信頼性の高いプログラムが作れます。
実践例:データ分析プログラム
最後に、ファイル操作を活用した実践的な例を見てみましょう。 簡単なデータ分析プログラムを作ってみます。
データの準備
def create_sample_data(): """分析用のサンプルデータを作成""" # 売上データを作成 sales_data = [ "日付,商品名,数量,単価", "2024-01-15,ノートPC,2,80000", "2024-01-16,マウス,5,2000", "2024-01-17,キーボード,3,5000", "2024-01-18,モニター,1,25000", "2024-01-19,ヘッドホン,4,8000" ] with open('sales_data.csv', 'w', encoding='utf-8') as file: for line in sales_data: file.write(line + '') print("サンプルデータを作成しました")
create_sample_data()
データ分析クラス
class SimpleDataAnalyzer: """シンプルなデータ分析クラス""" def __init__(self): self.data = [] def load_csv_data(self, filename): """CSVファイルを読み込み""" try: with open(filename, 'r', encoding='utf-8') as file: lines = file.readlines() # ヘッダー行を取得 if lines: headers = lines[0].strip().split(',') # データ行を辞書に変換 for line in lines[1:]: values = line.strip().split(',') if len(values) == len(headers): row = {} for i, header in enumerate(headers): row[header] = values[i] self.data.append(row) print(f"✅ データを読み込みました({len(self.data)}件)") return True except Exception as e: print(f"❌ データ読み込みエラー: {e}") return False def analyze_sales(self): """売上データを分析""" if not self.data: print("データがありません") return total_sales = 0 product_sales = {} for record in self.data: try: product = record['商品名'] quantity = int(record['数量']) price = int(record['単価']) sales = quantity * price total_sales += sales product_sales[product] = product_sales.get(product, 0) + sales except (KeyError, ValueError) as e: print(f"データ処理エラー: {e}") # 結果をファイルに出力 with open('sales_analysis.txt', 'w', encoding='utf-8') as file: file.write("売上分析レポート") file.write("=" * 30 + "
") file.write(f"総売上: {total_sales:,}円
") file.write("商品別売上:") for product, sales in sorted(product_sales.items(), key=lambda x: x[1], reverse=True): percentage = (sales / total_sales) * 100 file.write(f" {product}: {sales:,}円 ({percentage:.1f}%)") print("売上分析結果を sales_analysis.txt に保存しました") return total_sales, product_sales
# データ分析の実行print("=== データ分析の実行 ===")
analyzer = SimpleDataAnalyzer()
# データ読み込みif analyzer.load_csv_data('sales_data.csv'): # 分析実行 total, products = analyzer.analyze_sales() # 結果表示 print(f"総売上: {total:,}円") print("商品別売上:") for product, sales in products.items(): print(f" {product}: {sales:,}円")
# 分析結果ファイルの内容を確認show_file_content('sales_analysis.txt')
このように、ファイル操作を組み合わせることで、データの読み込み→処理→結果出力という実用的なプログラムが作れます。
まとめ:ファイル操作をマスターしよう
この記事では、Pythonのファイル操作について詳しく解説してきました。 最後に、重要なポイントをおさらいしましょう。
覚えておきたい基本
ファイル操作の基本パターン
with
文を使って安全にファイルを開閉する'r'
モードで読み込み、'w'
モードで書き込み、'a'
モードで追記encoding='utf-8'
を指定して文字化けを防ぐ
読み込み方法の使い分け
- 小さなファイルは
read()
で全体読み込み - 行ごとに処理したい場合は
for line in file:
- 大きなファイルは1行ずつ処理してメモリ節約
書き込み方法の使い分け
- 新規作成・上書きは
'w'
モード - 既存ファイルに追記は
'a'
モード - データの形式に応じて適切に整形
エラー対策も忘れずに
よくあるエラーの対処
FileNotFoundError
:ファイルが存在しないPermissionError
:書き込み権限がないUnicodeDecodeError
:文字エンコーディングの問題
安全な操作のために
try-except
文でエラーハンドリング- ファイルの存在確認を事前に行う
- 重要なファイルはバックアップを作成
実践で活用しよう
ファイル操作は、実際に使ってみることで身につきます。
こんなことから始めてみましょう
- 簡単な設定ファイルの読み書き
- 計算結果をファイルに保存
- ログファイルの作成
- CSVデータの処理
段階的にレベルアップ
- エラーハンドリングを組み込む
- バックアップ機能を追加
- データ分析プログラムを作成
- 他のファイル形式(JSON、XML)にも挑戦
次のステップ
基本的なファイル操作をマスターしたら、以下にも挑戦してみてください。
- CSVモジュールを使った高度なCSV処理
- JSONファイルの読み書き
- 設定ファイル(ini、yaml)の扱い
- ファイルパスの操作
- ディレクトリの作成と管理
最後に
ファイル操作は、プログラムを実用的にするための重要なスキルです。 最初は基本的な読み書きから始めて、徐々にエラーハンドリングや複雑なデータ処理に挑戦してみてください。
一度覚えてしまえば、プログラムの可能性が大きく広がります。 ぜひ、実際にコードを書いて試してみてくださいね。
頑張って、素晴らしいプログラムを作ってください!