Ing Python, kanggo maca lan nulis file, kita nggunakake fungsi kasedhiya ing perpustakaan standar lan cara kaya, lan. Mangkene carane manipulasi file ing: open()
read()
write()
close()
Python
Maca File
Kanggo maca file ing Python, kita nggunakake fungsi karo "r"(maca) mode. Fungsi iki ngasilake obyek file, banjur kita bisa nggunakake cara kaya kanggo maca isi file. open()
read()
Tuladha :
# Read the content of a file
with open("myfile.txt", "r") as file:
content = file.read()
print(content)
Nulis File
Kanggo nulis menyang file utawa nggawe file anyar, kita nggunakake fungsi kanthi mode "w"(tulis). Yen file kasebut wis ana, bakal ditimpa, yen ora, file anyar bakal digawe. open()
Tuladha :
# Write content to a file
with open("output.txt", "w") as file:
file.write("This is the content written to the file.")
Appending menyang File
Kanggo nambah isi menyang mburi file tanpa nimpa isi sing wis ana, kita nggunakake mode "a"(tambah).
Tuladha :
# Append content to a file
with open("logfile.txt", "a") as file:
file.write("Appending this line to the file.")
Nutup File
Sawise maca utawa nulis, dianjurake kanggo nutup file kanthi nggunakake close()
metode kasebut. Nanging, nalika nggunakake with
statement kasebut, ora perlu nutup file kanthi manual amarga Python bakal nutup file kanthi otomatis nalika metu saka with
blok kasebut.
Maca lan nulis file ing Python ngidini sampeyan nggarap data saka file lan nggawe aplikasi sing nyimpen lan ngolah informasi saka sumber eksternal.