Python 3エンジニア認定基礎試験-ファイル入出力(open()関数)-

1. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容: なし(ファイルは存在しない)
try:
with open('sample.txt', 'r') as f:
print(f.read())
except FileNotFoundError:
print("File not found")

2. 
次のコードで使用されているファイルモードに対応する操作を選んでください。

with open('sample.txt', 'a') as f:
f.write("Appended content")

3. 
次のコードで、ファイルを読み書きするために適切なモードを選んでください。

with open('sample.txt', ???) as f:
f.write("Content")
f.seek(0)
print(f.read())

4. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容: なし
with open('sample.txt', 'wb') as f:
print(f.writable())

5. 
次のコードで、ファイルのエンコーディングを指定する正しい方法を選んでください。

with open('sample.txt', 'w', ???) as f:
f.write("こんにちは")

6. 
次のコードで、バイナリモードでファイルを開くために適切なモードを選んでください。

with open('image.png', ???) as f:
data = f.read()

7. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容:
# ---
# Line1
# Line2
# ---
with open('sample.txt', 'a+') as f:
f.write("\nNew Line")
f.seek(0)
print(f.read())

8. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容: なし(ファイルは存在しない)
try:
with open('sample.txt', 'r+') as f:
f.write("Content")
except FileNotFoundError:
print("File not found")

9. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容:
# ---
# Hello, World!
# ---
with open('sample.txt', 'w+') as f:
f.write("New Content")
f.seek(0)
print(f.read())

10. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容:
# ---
# Line1
# ---
with open('sample.txt', 'a') as f:
print(f.readable())

11. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容:
# ---
# Initial
# ---
with open('sample.txt', 'r+') as f:
f.truncate(4)
print(f.read())

12. 
次のコードで、ファイルが存在しない場合に新規作成し、読み書きできるモードを選んでください。

with open('sample.txt', ???) as f:
f.write("New content")
f.seek(0)
print(f.read())

13. 
次のコードを実行したときに発生するエラーを選んでください。

with open('missing.txt', 'r') as f:
content = f.read()

14. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容:
# ---
# Line1
# ---
with open('sample.txt', 'r') as f:
print(f.writable())

15. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容:
# ---
# Line1
# Line2
# ---
with open('sample.txt', 'rb') as f:
print(f.read(5))

16. 
open()関数における第2引数で指定するファイルモードとして正しい組み合わせを選んでください。

17. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容: なし
with open('sample.txt', 'w') as f:
print(f.readable())

18. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容: なし(ファイルは存在しない)
with open('sample.txt', 'x') as f:
f.write("Exclusive Content")

19. 
次のコードの実行結果を選んでください。

# ファイル名: sample.txt
# 初期内容:
# ---
# Python is great!
# ---
with open('sample.txt', 'r+') as f:
f.seek(10)
f.write("amazing")
f.seek(0)
print(f.read())

20. 
次のコードで、'x'モードを使用した場合の動作を選んでください。

with open('sample.txt', 'x') as f:
f.write("Exclusive content")

コメントを残すにはログインしてください。