1.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容:
# ---
# Python is fun.
# ---
with open('sample.txt', 'r+') as f:
f.seek(10)
f.write("awesome!")
f.seek(0)
print(f.read())
2.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容: なし(ファイルは存在しない)
try:
with open('sample.txt', 'r+') as f:
f.write("Hello, World!")
except FileNotFoundError:
print("File not found")
3.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容:
# ---
# Line 1
# Line 2
# ---
with open('sample.txt', 'a') as f:
f.write("\nNew Line")
with open('sample.txt', 'r') as f:
print(f.read())
4.
with文を使用する主な目的として正しいものを選んでください。
5.
次のコードの実行結果を選んでください。
# sample.txt の初期内容:
# ---
# Line 1
# Line 2
# ---
with open('sample.txt', 'r') as f:
for line in f:
print(line.strip())
6.
次のコードの実行結果を選んでください。
# sample.txt の初期内容:
# ---
# Line 1
# Line 2
# ---
with open('sample.txt', 'r') as f:
content = f.read()
print(content)
7.
次のコードについて、with文を使用しない場合に注意が必要な点を選んでください。
f = open('sample.txt', 'r')
content = f.read()
f.close()
8.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容:
# ---
# Line 1
# Line 2
# ---
with open('sample.txt', 'r+') as f:
f.seek(7)
f.write("Modified")
f.seek(0)
print(f.read())
9.
次のコードについて、with文が持つ特性として正しいものを選んでください。
with open('logfile.txt', 'a') as log:
log.write("Log entry\n")
10.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容:
# ---
# Line1
# Line2
# ---
with open('sample.txt', 'a+') as f:
f.write("\nNew Line")
f.seek(0)
print(f.read())
11.
次のコードの実行結果について正しいものを選んでください。
with open('sample.txt', 'w') as f:
f.write("First Line\n")
raise Exception("An error occurred")
12.
次のコードで、with文を使うメリットとして正しいものを選んでください。
with open('sample.txt', 'r') as f:
content = f.read()
13.
次のコードで、with文を使用した場合に発生しない問題を選んでください。
f = open('sample.txt', 'w')
f.write("Test content")
# プログラムがここで終了した場合
14.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容: なし
with open('sample.txt', 'w') as f:
f.write("New Content")
with open('sample.txt', 'r') as f:
print(f.read())
15.
次のコードの実行結果を選んでください。
# sample.txt は存在しない
try:
with open('sample.txt', 'r') as f:
print(f.read())
except FileNotFoundError:
print("File not found")
16.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容:
# ---
# Line 1
# Line 2
# ---
with open('sample.txt', 'r+') as f:
f.seek(5)
f.write("Modified")
f.seek(0)
print(f.read())
17.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容: なし(ファイルは存在しない)
try:
with open('sample.txt', 'x') as f:
f.write("Exclusive Content")
except FileExistsError:
print("File already exists")
18.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容:
# ---
# Data Science
# ---
with open('sample.txt', 'r+') as f:
f.seek(5)
f.truncate()
f.seek(0)
print(f.read())
19.
次のコードについて、with文を使用して書き換えた正しい方法を選んでください。
f = open('sample.txt', 'w')
f.write("Hello, World!")
f.close()
20.
次のコードを実行したとき、with文を使用する理由として最も適切なものを選んでください。
with open('data.txt', 'w') as f:
for i in range(5):
f.write(f"Line {i}\n")