Python でテキストファイルの読み書き機能をサポートするクラスを実装する
という名前のクラスを作成します。TextFileHandlerこのクラスはテキストファイルの読み書き機能をサポートします。このクラスには2つの主要なメソッドが含まれます。read_fileファイルの内容を読み取るために使用されます。write_file内容をファイルに書き込むために使用されます。
例
class TextFileHandler:
def __init__(self, filename):
self.filename = filename
def read_file(self):
try:
with open(self.filename, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
return "File not found."
def write_file(self, content):
with open(self.filename, 'w') as file:
file.write(content)
return "File written successfully."
# 使用例
handler = TextFileHandler('example.txt')
handler.write_file("Hello, World!")
print(handler.read_file())
def __init__(self, filename):
self.filename = filename
def read_file(self):
try:
with open(self.filename, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
return "File not found."
def write_file(self, content):
with open(self.filename, 'w') as file:
file.write(content)
return "File written successfully."
# 使用例
handler = TextFileHandler('example.txt')
handler.write_file("Hello, World!")
print(handler.read_file())
コード解析:
__init__メソッド:これはクラスのコンストラクターであり、クラスのインスタンスを初期化するために使用されます。ファイル名をパラメータとして受け取り、それをインスタンス変数にself.filename格納します。read_fileメソッド:このメソッドはファイルの内容を読み取るために使用されます。これはwith openステートメントを使用して読み取り専用モードでファイルを開き、ファイルの内容を読み取ります。ファイルが存在しない場合は、FileNotFoundError例外を捕捉し、"File not found." を返します。write_fileメソッド:このメソッドは内容をファイルに書き込むために使用されます。これはwith openステートメントを使用して書き込みモードでファイルを開き、渡された内容をファイルに書き込みます。書き込みが成功すると、"File written successfully." を返します。
出力結果:
Hello, World!その他の拡張
Python3 の例