- Pythonプログラム練習問題10問:ファイル操作編 - 初心者向け徹底解説
- 前提知識:ファイルとは?
- ファイル操作の基本:open()関数とモード
- ファイルのクローズ:close()関数
- 練習問題1:ファイルを作成し、文字列を書き込む
- 練習問題2:ファイルから文字列を読み込む
- 練習問題3:ファイルから1行ずつ読み込む
- 練習問題4:ファイルに追記する
- 練習問題5:CSVファイルの読み込み
- 練習問題6:CSVファイルへの書き込み
- 練習問題7:JSONファイルの読み込み
- 練習問題8:JSONファイルへの書き込み
- 練習問題9:ファイルサイズの確認
- 練習問題10:バイナリファイルの読み込みと書き込み
- Python Programming Practice Problems: File Operations (10 Questions for Beginners - Thorough Explanation)
- Problem 1: Create a File and Write a String
- Problem 2: Read a String from a File
- Problem 3: Read a File Line by Line
- Problem 4: Append to a File
- Problem 5: Read a CSV File
- Problem 6: Write to a CSV File
- Problem 7: Read a JSON File
- Problem 8: Write to a JSON File
- Problem 9: Check File Size
- Problem 10: Read and Write a Binary File
Pythonプログラム練習問題10問:ファイル操作編 - 初心者向け徹底解説
Pythonは汎用性の高いプログラミング言語であり、その強力な機能の一つがファイル操作です。テキストファイルの読み書きはもちろん、CSVやJSONといった構造化データの処理も容易に行えます。本記事では、Pythonのファイル操作に関する練習問題を10問取り上げ、初心者の方でも理解しやすいように丁寧に解説します。
前提知識:ファイルとは?
コンピュータ上でデータを保存する場所を「ファイル」と呼びます。ファイルには様々な種類があり、テキストデータ(.txt, .csv, .logなど)、画像データ(.jpg, .pngなど)、音声データ(.mp3, .wavなど)などがあります。Pythonでは、これらのファイルをプログラムから読み込んだり、書き込んだりすることができます。
What is a File?
In computer science, a file is a named collection of data stored on a storage device (like a hard drive or SSD). Files come in various formats, including text files (.txt, .csv, .log), image files (.jpg, .png), audio files (.mp3, .wav), and many more. Python allows you to interact with these files programmatically, reading data from them and writing data to them.
ファイル操作の基本:open()
関数とモード
Pythonでファイルを扱うための最初のステップは、open()
関数を使ってファイルを開くことです。open()
関数は、ファイル名と「モード」という引数を取ります。モードは、ファイルを開く目的(読み込み、書き込み、追加など)を指定します。主なモードは以下の通りです。
- 'r': 読み込み専用 (Read)。ファイルが存在しない場合はエラーが発生します。
- 'w': 書き込み専用 (Write)。ファイルが存在する場合は内容が上書きされ、存在しない場合は新規作成されます。
- 'a': 追加モード (Append)。ファイルが存在する場合は末尾に追記され、存在しない場合は新規作成されます。
- 'x': 排他的な作成 (Exclusive Creation)。ファイルが存在する場合エラーが発生し、存在しない場合に新規作成されます。
- 'b': バイナリモード (Binary)。画像や音声データなど、テキスト以外のファイルを扱う際に使用します。
- 't': テキストモード (Text)。デフォルトのモードです。テキストデータを扱う際に使用します。
- '+': 読み書き両用 (Read and Write)。上記のモードと組み合わせて使用します(例: 'r+')。
open()
関数の基本的な構文は以下の通りです。
file_object = open(filename, mode)
ここで、filename
は開きたいファイルの名前(パスを含む)、mode
はファイルの開き方を指定する文字列です。
Basic File Operations: The open()
Function and Modes
The first step in working with files in Python is to open them using the open()
function. This function takes two main arguments: the filename (including its path) and a mode string that specifies how you want to open the file. Here's a breakdown of common modes:
- 'r': Read Mode - Opens the file for reading only. An error occurs if the file doesn’t exist.
- 'w': Write Mode - Opens the file for writing. If the file exists, its contents are overwritten. If it doesn't exist, a new file is created.
- 'a': Append Mode - Opens the file for appending data to the end. If the file exists, new data is added after the existing content. If it doesn’t exist, a new file is created.
- 'x': Exclusive Creation Mode - Creates a new file but raises an error if the file already exists.
- 'b': Binary Mode - Used for handling non-text files like images and audio files. It opens the file in binary format.
- 't': Text Mode - The default mode. It handles text files, automatically decoding bytes into strings.
- '+': Read and Write Mode - Combines one of the above modes with read/write capabilities (e.g., 'r+' for reading and writing).
The basic syntax of open()
is:
file_object = open(filename, mode)
Where filename
is the name of the file you want to open (including its path), and mode
is a string specifying how you want to open the file.
ファイルのクローズ:close()
関数
ファイル操作が終わったら、必ずclose()
関数を使ってファイルを閉じましょう。ファイルを閉じることで、リソースの解放やデータの整合性を保つことができます。with
ステートメントを使用すると、自動的にファイルが閉じられるため、より安全なコードを書くことができます。
# ファイルを閉じる方法1: close()関数を使う file = open("my_file.txt", "r") content = file.read() print(content) file.close() # ファイルを閉じる方法2: withステートメントを使う (推奨) with open("my_file.txt", "r") as file: content = file.read() print(content)
with
ステートメントを使用する利点は、例外が発生した場合でもファイルが確実に閉じられることです。 with
ブロックを抜ける際に、自動的に file.close()
が呼び出されます。
Closing Files: The close()
Function
After you're finished working with a file, it’s crucial to close it using the close()
function. Closing a file releases system resources and ensures that any buffered data is written to disk properly. A safer and more Pythonic way to handle this is by using the with
statement:
# Method 1: Using the close() function file = open("my_file.txt", "r") content = file.read() print(content) file.close() # Method 2: Using the with statement (recommended) with open("my_file.txt", "r") as file: content = file.read() print(content)
The advantage of using the with
statement is that it guarantees the file will be closed, even if an exception occurs within the block. When exiting the with
block, file.close()
is automatically called.
練習問題1:ファイルを作成し、文字列を書き込む
まず、"output.txt"
という名前のファイルを書き込みモード ('w'
) で開き、そのファイルに "Hello, world!"
という文字列を書き込みましょう。
with open("output.txt", "w") as file: file.write("Hello, world!")
Problem 1: Create a File and Write a String
First, create a file named "output.txt"
in write mode ('w'
) and write the string "Hello, world!"
to it.
with open("output.txt", "w") as file: file.write("Hello, world!")
練習問題2:ファイルから文字列を読み込む
"output.txt"
という名前のファイルを読み込みモード ('r'
) で開き、そのファイルの内容を変数に格納し、画面に出力しましょう。
with open("output.txt", "r") as file: content = file.read() print(content)
Problem 2: Read a String from a File
Open the file named "output.txt"
in read mode ('r'
), store its contents in a variable, and print it to the screen.
with open("output.txt", "r") as file: content = file.read() print(content)
練習問題3:ファイルから1行ずつ読み込む
"output.txt"
という名前のファイルを読み込みモード ('r'
) で開き、そのファイルから1行ずつ読み込み、それぞれの行を画面に出力しましょう。
with open("output.txt", "r") as file: for line in file: print(line.strip()) # 行末の改行文字を取り除く
line.strip()
は、各行の先頭と末尾にある空白文字(スペース、タブ、改行など)を削除します。これにより、出力がよりきれいに表示されます。
Problem 3: Read a File Line by Line
Open the file named "output.txt"
in read mode ('r'
) and read it line by line, printing each line to the screen.
with open("output.txt", "r") as file: for line in file: print(line.strip()) # Removes leading/trailing whitespace from each line
line.strip()
removes any leading or trailing whitespace (spaces, tabs, newlines) from each line, resulting in cleaner output.
練習問題4:ファイルに追記する
"output.txt"
という名前のファイルを追記モード ('a'
) で開き、そのファイルに "This is a new line."
という文字列を書き込みましょう。
with open("output.txt", "a") as file: file.write("\nThis is a new line.") # 改行文字を追加
追記モードでは、既存のファイルの内容は上書きされず、新しいデータがファイルの末尾に追加されます。\n
は改行文字を表し、新しい行を開始するために使用します。
Problem 4: Append to a File
Open the file named "output.txt"
in append mode ('a'
) and write the string "This is a new line."
to it.
with open("output.txt", "a") as file: file.write("\nThis is a new line.") # Adds a newline character
In append mode, existing content in the file remains unchanged; new data is added to the end of the file. \n
represents a newline character and is used to start a new line.
練習問題5:CSVファイルの読み込み
"data.csv"
という名前のCSVファイル(以下のような内容)を読み込みモード ('r'
) で開き、各行のデータをリストとして格納し、画面に出力しましょう。
name,age,city Alice,30,New York Bob,25,London Charlie,40,Tokyo
CSV (Comma Separated Values) ファイルは、表形式のデータを保存するために広く使用されています。Python の csv
モジュールを使用すると、CSV ファイルを簡単に読み書きできます。
Problem 5: Read a CSV File
Open the CSV file named "data.csv"
(with content like below) in read mode ('r'
) and store each row of data as a list, then print it to the screen.
name,age,city Alice,30,New York Bob,25,London Charlie,40,Tokyo
CSV (Comma Separated Values) files are widely used for storing tabular data. Python's csv
module makes it easy to read and write CSV files.
import csv with open("data.csv", "r") as file: reader = csv.reader(file) header = next(reader) # ヘッダー行を読み飛ばす for row in reader: print(row)
csv.reader()
は、CSV ファイルの内容を読み込み、各行をリストとして返します。 next(reader)
を使用してヘッダー行(列名)を読み飛ばし、データ行のみを処理しています。
練習問題6:CSVファイルへの書き込み
"output.csv"
という名前のCSVファイルを作成し、以下のデータを書き込みモード ('w'
) で書き込みましょう。
name,age,city David,35,Paris Eve,28,Sydney
Problem 6: Write to a CSV File
Create a CSV file named "output.csv"
and write the following data to it in write mode ('w'
):
name,age,city David,35,Paris Eve,28,Sydney
import csv data = [ ["David", 35, "Paris"], ["Eve", 28, "Sydney"] ] with open("output.csv", "w", newline="") as file: writer = csv.writer(file) writer.writerow(["name", "age", "city"]) # ヘッダー行を書き込む writer.writerows(data) # データを書き込む
newline=""
は、CSV ファイルに余分な空行が挿入されるのを防ぐために重要です。 csv.writer()
は、データを CSV ファイルに書き込むためのオブジェクトを作成します。 writerow()
を使用してヘッダー行を書き込み、 writerows()
を使用して複数のデータ行を一度に書き込みます。
練習問題7:JSONファイルの読み込み
"data.json"
という名前のJSONファイル(以下のような内容)を読み込みモード ('r'
) で開き、そのファイルの内容をPythonの辞書として格納し、画面に出力しましょう。
{ "name": "John Doe", "age": 30, "city": "Chicago" }
JSON (JavaScript Object Notation) は、データを保存および交換するための軽量な形式です。Python の json
モジュールを使用すると、JSON ファイルを簡単に読み書きできます。
Problem 7: Read a JSON File
Open the JSON file named "data.json"
(with content like below) in read mode ('r'
), store its contents as a Python dictionary, and print it to the screen.
{ "name": "John Doe", "age": 30, "city": "Chicago" }
JSON (JavaScript Object Notation) is a lightweight format for storing and exchanging data. Python's json
module makes it easy to read and write JSON files.
import json with open("data.json", "r") as file: data = json.load(file) print(data)
json.load()
関数は、JSON ファイルの内容を読み込み、Python の辞書またはリストとして返します。
練習問題8:JSONファイルへの書き込み
"output.json"
という名前のJSONファイルを作成し、以下のデータを書き込みモード ('w'
) で書き込みましょう。
{ "name": "Jane Smith", "age": 25, "city": "Los Angeles" }
Problem 8: Write to a JSON File
Create a JSON file named "output.json"
and write the following data to it in write mode ('w'
):
{ "name": "Jane Smith", "age": 25, "city": "Los Angeles" }
import json data = { "name": "Jane Smith", "age": 25, "city": "Los Angeles" } with open("output.json", "w") as file: json.dump(data, file, indent=4) # indent=4 はJSONを整形して書き込むため
json.dump()
関数は、Python の辞書またはリストを JSON ファイルに書き込みます。 indent=4
引数は、JSON データを読みやすくするためにインデントを追加します。
練習問題9:ファイルサイズの確認
"large_file.txt"
という名前のファイルを読み込みモード ('r'
) で開き、そのファイルのサイズ(バイト数)を確認し、画面に出力しましょう。
Problem 9: Check File Size
Open the file named "large_file.txt"
in read mode ('r'
) and determine its size (in bytes). Print the size to the screen.
import os with open("large_file.txt", "r") as file: size = os.path.getsize(file.name) print(f"ファイルサイズ: {size} バイト")
os.path.getsize()
関数は、指定されたファイルのサイズをバイト単位で返します。
練習問題10:バイナリファイルの読み込みと書き込み
"image.jpg"
という名前の画像ファイルを読み込みモード ('rb'
) で開き、その内容を別のファイル "copy_image.jpg"
という名前で書き込みモード ('wb'
) で書き出しましょう。
Problem 10: Read and Write a Binary File
Open the image file named "image.jpg"
in read binary mode ('rb'
) and write its contents to another file named "copy_image.jpg"
in write binary mode ('wb'
).
with open("image.jpg", "rb") as infile, open("copy_image.jpg", "wb") as outfile: outfile.write(infile.read())
バイナリファイル(画像、音声、動画など)を扱う場合は、'rb'
(read binary) および 'wb'
(write binary) モードを使用する必要があります。これにより、データがテキストとしてではなく、そのままのバイト列として読み書きされます。
まとめと補足
本記事では、Pythonのファイル操作に関する基本的な練習問題を10問取り上げました。これらの問題を通して、ファイルの読み込み、書き込み、追記、CSV/JSONデータの処理など、様々なファイル操作の方法を学ぶことができたはずです。
- エラーハンドリング: ファイルが存在しない場合や、アクセス権がない場合にプログラムがクラッシュしないように、
try-except
ブロックを使ってエラーハンドリングを行うことを推奨します。 - エンコーディング: テキストファイルを扱う際には、ファイルのエンコーディング(UTF-8, Shift_JISなど)を考慮する必要があります。
open()
関数のencoding
引数で指定できます。 - ファイルパス: ファイル名を直接指定するのではなく、絶対パスや相対パスを使ってファイルを特定することを推奨します。
これらの練習問題を参考に、さらに様々なファイル操作に挑戦し、Pythonプログラミングのスキルを向上させてください。
参照先:
- Python公式ドキュメント -
open()
: https://docs.python.org/ja/3/library/functions.html#open - Python公式ドキュメント -
csv
: https://docs.python.org/ja/3/library/csv.html - Python公式ドキュメント -
json
: https://docs.python.org/ja/3/library/json.html - Python公式ドキュメント -
os.path.getsize()
: https://docs.python.org/ja/3/library/os.path.html#os.path.getsize
これらのリソースを活用して、ファイル操作に関する理解を深めてください。
English Translation:
Python Programming Practice Problems: File Operations (10 Questions for Beginners - Thorough Explanation)
This article presents 10 practice problems related to file operations in Python, designed specifically for beginners. We will provide a detailed explanation of each problem to ensure you understand the concepts thoroughly.
Prerequisites: What is a File?
A "file" is a location on a computer where data is stored. Files come in various types, including text files (.txt, .csv, .log), image files (.jpg, .png), and audio files (.mp3, .wav). Python allows you to read from and write to these files within your programs.
File Operation Basics: The open()
Function and Modes
The first step in working with files in Python is opening them using the open()
function. The open()
function takes two arguments: the filename and a "mode" that specifies the purpose of opening the file (reading, writing, appending, etc.). Here are the main modes:
- 'r': Read-only (Read). Raises an error if the file does not exist.
- 'w': Write-only (Write). Overwrites the contents of the file if it exists; creates a new file if it doesn’t.
- 'a': Append mode (Append). Adds data to the end of the file if it exists; creates a new file if it doesn’t.
- 'x': Exclusive creation (Exclusive Creation). Raises an error if the file already exists; creates a new file if it doesn’t.
- 'b': Binary mode (Binary). Used for handling files that are not text, such as images and audio data.
- 't': Text mode (Text). The default mode. Used for handling text data.
- '+': Read and Write (Read and Write). Combines with other modes to allow both reading and writing (e.g., 'r+' ).
Closing Files: The close()
Function
After you finish working with a file, it’s crucial to close it using the close()
function. Closing the file releases resources and ensures data integrity. Using the with
statement is recommended as it automatically closes the file when the block of code finishes executing.
# Method 1: Using the close() function file = open("my_file.txt", "r") content = file.read() print(content) file.close() # Method 2: Using the with statement (recommended) with open("my_file.txt", "r") as file: content = file.read() print(content)
Problem 1: Create a File and Write a String
Create a file named "output.txt"
in write mode ('w'
) and write the string "Hello, world!"
to it.
with open("output.txt", "w") as file: file.write("Hello, world!")
Problem 2: Read a String from a File
Open the file named "output.txt"
in read mode ('r'
), store its contents in a variable, and print it to the screen.
with open("output.txt", "r") as file: content = file.read() print(content)
Problem 3: Read a File Line by Line
Open the file named "output.txt"
in read mode ('r'
) and read it line by line, printing each line to the screen.
with open("output.txt", "r") as file: for line in file: print(line.strip()) # Removes leading/trailing whitespace from each line
Problem 4: Append to a File
Open the file named "output.txt"
in append mode ('a'
) and write the string "This is a new line."
to it.
with open("output.txt", "a") as file: file.write("\nThis is a new line.") # Adds a newline character
Problem 5: Read a CSV File
Open the CSV file named "data.csv"
(with content like below) in read mode ('r'
) and store each row of data as a list, then print it to the screen.
name,age,city Alice,30,New York Bob,25,London Charlie,40,Tokyo
Problem 6: Write to a CSV File
Create a CSV file named "output.csv"
and write the following data to it in write mode ('w'
):
name,age,city David,35,Paris Eve,28,Sydney
Problem 7: Read a JSON File
Open the JSON file named "data.json"
(with content like below) in read mode ('r'
), store its contents as a Python dictionary, and print it to the screen.
{ "name": "John Doe", "age": 30, "city": "Chicago" }
Problem 8: Write to a JSON File
Create a JSON file named "output.json"
and write the following data to it in write mode ('w'
):
{ "name": "Jane Smith", "age": 25, "city": "Los Angeles" }
Problem 9: Check File Size
Open the file named "large_file.txt"
in read mode ('r'
) and check its size (in bytes), printing it to the screen.
Problem 10: Read and Write a Binary File
Open the image file named "image.jpg"
in read binary mode ('rb'
) and write its contents to another file named "copy_image.jpg"
in write binary mode ('wb'
).
Conclusion and Additional Notes
This article presented 10 practice problems related to basic file operations in Python. Through these exercises, you’ve learned various methods for reading from, writing to, appending to, and processing CSV/JSON data files.
- Error Handling: Use
try-except
blocks to handle potential errors like non-existent files or insufficient permissions, preventing your program from crashing. - Encoding: When working with text files, consider the file's encoding (UTF-8, Shift_JIS, etc.). You can specify it using the
encoding
argument in theopen()
function. - File Paths: Instead of directly specifying filenames, use absolute or relative paths to identify files more reliably.
Continue practicing with various file operations and enhance your Python programming skills based on these exercises.
References:
- Python Official Documentation -
open()
: https://docs.python.org/ja/3/library/functions.html#open - Python Official Documentation -
csv
: https://docs.python.org/ja/3/library/csv.html - Python Official Documentation -
json
: https://docs.python.org/ja/3/library/json.html - Python Official Documentation -
os.path.getsize()
: https://docs.python.org/ja/3/library/os.path.html#os.path.getsize
Utilize these resources to deepen your understanding of file operations.