Daftar Referensi Python
close() adalah method file untuk mengosongkan buffer lalu menutup stream. Setelah file ditutup, operasi baca atau tulis biasanya menghasilkan ValueError.
Sintaks
file.close()
Parameter
| Parameter | Wajib? | Keterangan |
|---|---|---|
| – | – | close() tidak menerima parameter |
Nilai balik: None. Properti file.closed menjadi True.
Contoh
file = open("status.txt", "w", encoding="utf-8")
print(file.closed)
file.close()
print(file.closed)
Output:
False
True
Contoh Lainnya
close() boleh dipanggil lebih dari sekali
from io import StringIO
file = StringIO("Python")
file.close()
file.close()
print(file.closed)
Output:
True
Operasi setelah close() menghasilkan error
from io import StringIO
file = StringIO()
file.close()
try:
file.write("data")
except ValueError:
print("file sudah ditutup")
Output:
file sudah ditutup
Blok with menutup file otomatis
with open("otomatis.txt", "w", encoding="utf-8") as file:
file.write("selesai")
print(file.closed)
print(file.closed)
Output:
False
True
Kesalahan Umum
- Lupa menutup file dapat menunda penulisan buffer dan memakai resource lebih lama.
- Membaca atau menulis setelah
close()menghasilkanValueError: I/O operation on closed file. - Untuk pemakaian biasa, utamakan blok
withagar file tetap ditutup ketika terjadi exception. - Memanggil
close()berulang tidak menghasilkan error, tetapi hanya pemanggilan pertama yang berpengaruh.
Pelajari Lebih Lanjut
- Referensi: with di Python · open() di Python · write() di Python
- Buku Belajar Python untuk Pemula: Bab 14
