Daftar Referensi Python
flush() memaksa data yang masih berada di buffer ditulis ke stream dasar tanpa menutup file.
Sintaks
file.flush()
Parameter
| Parameter | Wajib? | Keterangan |
|---|---|---|
| – | – | flush() tidak menerima parameter |
Nilai balik: None.
Contoh
from io import BytesIO
file = BytesIO()
file.write(b"Python")
print(file.flush())
Output:
None
Contoh Lainnya
Stream tetap terbuka
from io import StringIO
file = StringIO()
file.write("data")
file.flush()
print(file.closed)
print(file.getvalue())
Output:
False
data
Boleh dipanggil berulang
from io import BytesIO
file = BytesIO(b"ABC")
file.flush()
file.flush()
print(file.getvalue())
Output:
b'ABC'
Flush setelah ditutup
import tempfile
file = tempfile.TemporaryFile(mode="w+")
file.close()
try:
file.flush()
except ValueError:
print("stream sudah ditutup")
Output:
stream sudah ditutup
Kesalahan Umum
flush()tidak menutup file.close()juga melakukan flush sebelum menutup.- Flush pada stream tertutup menghasilkan
ValueError.
Pelajari Lebih Lanjut
- Referensi: close() · write() · with
- Buku Belajar Python untuk Pemula: Bab 14
