1.
次のコードの実行結果を選んでください。
# sample.txt の初期内容:
# ---
# Old Content
# ---
with open('sample.txt', 'w') as f:
f.write("New Content")
2.
次のコードを実行したときのsample.txtの内容を選んでください。
with open('sample.txt', 'a') as f:
f.write("Appended Text\n")
3.
次のコードの実行結果を選んでください。
# sample.txt は存在しない
try:
with open('sample.txt', 'w+') as f:
f.write("Testing w+ mode")
f.seek(0)
print(f.read())
except Exception as e:
print(f"Error: {e}")
4.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容:
# ---
# Line1
# ---
with open('sample.txt', 'w') as f:
f.write("New Line")
f.seek(0)
f.write("Old")
5.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
with open('sample.txt', 'w') as f:
lines = ["Line1\n", "Line2\n", "Line3\n"]
f.writelines(lines)
6.
次のコードを実行したときのsample.txtの内容を選んでください。
with open('sample.txt', 'w') as f:
f.write("Hello, World!\n")
f.write("Python Programming")
7.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容:
# ---
# Line1
# Line2
# ---
with open('sample.txt', 'r+') as f:
f.seek(6)
f.write("Modified")
f.seek(0)
print(f.read())
8.
次のコードの実行結果を選んでください。
# sample.txt は存在しない
try:
with open('sample.txt', 'r+') as f:
f.write("Hello, World!")
except FileNotFoundError:
print("File not found")
9.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
with open('sample.txt', 'w') as f:
f.write("First Line\n")
f.flush()
f.write("Second Line\n")
10.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容:
# ---
# Line1
# ---
with open('sample.txt', 'a') as f:
f.write("Line2\n")
11.
次のコードの実行結果を選んでください。
# sample.txt
# 初期内容: なし
try:
with open('sample.txt', 'x') as f:
f.write("New File Content")
f.write("\nSecond Line")
except FileExistsError:
print("File already exists")
12.
次のコードで、ファイルがすでに存在している場合に発生する挙動を選んでください。
# ファイル名: sample.txt
with open('sample.txt', 'x') as f:
f.write("Exclusive write mode")
13.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容: なし(ファイルは存在しない)
with open('sample.txt', 'a') as f:
f.write("Hello, World!")
14.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容:
# ---
# Line1
# Line2
# ---
with open('sample.txt', 'w') as f:
f.writelines(["New1\n", "New2\n", "New3\n"])
15.
次のコードを実行したときのエラーを防ぐ方法を選んでください。
# ファイル名: missing_folder/sample.txt
with open('missing_folder/sample.txt', 'w') as f:
f.write("Hello, World!")
16.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
# 初期内容:
# ---
# Line1
# Line2
# ---
with open('sample.txt', 'r+') as f:
f.write("New")
f.seek(6)
f.write("Content")
17.
次のコードにおいて、テキストファイルにデータを書き込むための正しい方法を選んでください。
# ファイル名: sample.txt
with open('sample.txt', ???) as f:
f.write("Hello, World!")
18.
次のコードの実行結果を選んでください。
# ファイル名: sample.txt
with open('sample.txt', 'w') as f:
f.write("Line1\n")
f.write("Line2\n")
print(f.tell())
19.
次のコードの実行結果を選んでください。
# sample.txt
# ---
# Initial Content
# ---
with open('sample.txt', 'w') as f:
f.truncate(5)
20.
次のコードの実行結果を選んでください。
# sample.txt
# ---
# Initial Line
# ---
with open('sample.txt', 'a+') as f:
f.write("\nAppended Line")
f.seek(0)
print(f.read())