.readlines()
入力ファイルがメモリに問題なく収まることがわかっている場合にのみ使用してください。一度にすべての行を読み取ります。
ほとんどの場合、一度に 1 つの入力行を読み取ることができます。そのためには、ファイル ハンドル オブジェクトを反復処理するだけです。
特別でトリッキーな入力処理が必要な場合は、次のようなジェネレーター関数で処理をカプセル化することをお勧めします。
def do_something_with_point(point):
print(point)
class BadInputFile(ValueError):
pass
def read_points_data(f):
try:
line = next(f)
if not line.startswith("#Name"):
raise BadInputFile("file does not start with #Name")
line = next(f)
if not line.startswith("#main"):
raise BadInputFile("second line does not start with #main")
except StopIteration:
raise BadInputFile("truncated input file")
# use enumerate() to count input lines; start at line number 3
# since we just handled two lines of header
for line_num, line in enumerate(f, 3):
if line.startswith("#extra"):
break
else:
try:
yield int(line)
except ValueError:
raise BadInputFile("illegal line %d: %s" % (line_num, line))
# if you really do want strings: yield line
else:
# this code will run if we never see a "#extra" line
# if break is executed, this doesn't run.
raise BadInputFile("#extra not seen")
try:
line = next(f)
if not line.startswith("!side"):
raise BadInputFile("!side not seen after #extra")
except StopIteration:
raise BadInputFile("input file truncated after #extra")
with open("points_input_file.txt") as f:
for point in read_points_data(f):
do_something_with_point(point)
この入力関数は入力を完全に検証し、入力に誤りがある場合は例外を発生させることに注意してください。しかし、入力データを使用するループは単純でクリーンです。使用するコードをread_points_data()
整理できます。
入力ポイントを値にread_points_data()
変換しました。int
ポイントを文字列として本当に必要な場合は、コードを変更できます。私はあなたに思い出させるためにそこにコメントを残しました。