pythonベース9-ファイルと例外
3067 ワード
ファイル全体を読み込む
注意:withの使い方:ファイルを適切に開いたり閉じたりします.rstrip()関数:空の行でファイルを使用する内容を削除します.
注意:pythonは、テキストファイルを読み込むと、すべてのテキストを文字列として解読します.数字を読み取る場合はint()で整数に変換し、関数float()で浮動小数点数に変換する必要があります.誕生日が円周率に含まれているかどうか
ファイルの書き込み
注意:open関数のいくつかのモード:r:読み取りモード.w:書き込みモードa:添付ファイルモードで、既存のベースに他のコンテンツを追加できます.複数行の注意書き:改行記号.
複数のファイルを使用し、失敗したときは一言も言わない.
try,exceptの使い方:tryコードブロックのコード実行に問題がなければ、Pythonはexceptコードブロックをスキップします.tryコードの実行が間違っている場合、pythonはこのようなexceptモジュールを検索し、コードを実行します.try,except,elseモジュールではtry実行に失敗し,exceptを実行し,実行に成功し,elseモジュールを実行する.
どのエラーを報告するかを決定し、ユーザーのニーズによって決定します.
ストレージデータはjsonを使用してデータを格納します.
再構築コードを特定の作業を完了する一連の関数に分割します.このようなプロセスを再構成と呼ぶ.再構築により、コードがより明確になり、理解しやすくなり、拡張しやすくなります.
with open('pi_digits.txt') as file_object:
contents = file_object.read()
print(contents.rstrip())
注意:withの使い方:ファイルを適切に開いたり閉じたりします.rstrip()関数:空の行でファイルを使用する内容を削除します.
with open('test_files/pi_digits.txt') as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
print(pi_string)
print(len(pi_string))
注意:pythonは、テキストファイルを読み込むと、すべてのテキストを文字列として解読します.数字を読み取る場合はint()で整数に変換し、関数float()で浮動小数点数に変換する必要があります.誕生日が円周率に含まれているかどうか
with open('pi_million_digits.txt') as file_object:
lines = file_object.readlines()
pi_string = ''
for line in lines:
pi_string += line.strip()
birthday = input("Enter your bithday:")
if birthday in pi_string:
print("your birtday appears.")
else:
print("your birthday don't appear.")
#print(pi_string[:6] + "...")
print(len(pi_string))
ファイルの書き込み
filename = 'programing.txt'
with open(filename,'a') as file_object:
file_object.write("I also love you.
")
file_object.write("I also love programing.
")
注意:open関数のいくつかのモード:r:読み取りモード.w:書き込みモードa:添付ファイルモードで、既存のベースに他のコンテンツを追加できます.複数行の注意書き:改行記号.
複数のファイルを使用し、失敗したときは一言も言わない.
try,exceptの使い方:tryコードブロックのコード実行に問題がなければ、Pythonはexceptコードブロックをスキップします.tryコードの実行が間違っている場合、pythonはこのようなexceptモジュールを検索し、コードを実行します.try,except,elseモジュールではtry実行に失敗し,exceptを実行し,実行に成功し,elseモジュールを実行する.
def count_number(filename):
try:
with open(filename) as f_obj:
contents = f_obj.read()
except FileNotFoundError:
pass
else:
words = contents.split()
number_words = len(words)
print("The novel " + filename +" has " + str(number_words) + ".")
filenames = ['alice.txt','sidd.txt','moby_dict.txt','little_women.txt']
for filename in filenames:
count_number(filename)
どのエラーを報告するかを決定し、ユーザーのニーズによって決定します.
ストレージデータはjsonを使用してデータを格納します.
import json
def stored_username():
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username
def get_new_name():
username = input("What's your name?")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
return username
def greet_user():
username = stored_username()
if username:
print("welcome back," + username + "!")
else:
username = get_new_name()
print("We will be happy,when you come," + username + "!")
greet_user()
再構築コードを特定の作業を完了する一連の関数に分割します.このようなプロセスを再構成と呼ぶ.再構築により、コードがより明確になり、理解しやすくなり、拡張しやすくなります.