Penanganan File Python

Ing kiriman iki, kita bakal ngrembug babagan cara nangani File Python. Contone kode ing ngisor iki nuduhake cara nggawe, maca, nulis lan mbusak file ing Python.



Cara Nggawe File ing Python

Kanggo nggawe file ing Python, kita nggunakake open() cara, sing njupuk rong paramèter: jeneng file lan salah sawijining mode: 'x', 'a', 'w'.

'x' digunakake kanggo nggawe file anyar. Ana kesalahan sing diluncurake yen ana file kasebut. 'a' lan 'w' digunakake kanggo nambah file lan nulis menyang file, nanging yen file ora ana, mula file kasebut bakal digawe.


Tuladha:

file = open('somefile.txt', 'x')

File anyar somefile.txt digawe




Cara Maca File ing Python

Kanggo maca file ing Python, kita nggunakake open() fungsi, maringake ing jeneng file lan 'r' kanggo mode maca.



Tuladha: waca file sing diarani somefile.txt

Isinipun somefile.txt:

Hello!! Welcome to Python Goodbye. file = open('somefile.txt', 'r') print(file.read()) file.close()

Output:


Hello!! Welcome to Python Goodbye.

Cara Maca Bagian File ing Python

Kita bisa maca bagean file kanthi pass ing jumlah karakter menyang read() cara Contone:

file = open('somefile.txt', 'r') print(file.read(5)) file.close()

Output:

Hello

Cara Maca Baris File Kanthi Baris

Kita bisa nggunakake readline() cara kanggo maca saben baris file.

Maca Mung Siji Baris

file = open('somefile.txt', 'r') print(file.readline()) file.close

Output:


Hello!!

Waca Loro Baris

file = open('somefile.txt', 'r') print(file.readline()) print(file.readline()) file.close

Output:

Hello!! Welcome to Python

Waca Kabeh Garis

Kita bisa nggunakake for daur ulang kanggo maca kabeh baris file:

file = open('somefile.txt', 'r') for x in file:
print(x)

Output:

Hello!! Welcome to Python Goodbye

Cara Nulis File ing Python

Kanggo nulis menyang file, maneh nggunakake open() cara nganggo jeneng file minangka parameter pisanan lan 'a' utawa 'w' minangka paramèter nomer loro.


'a' bakal nambah data menyang file sing wis ditemtokake. 'w' bakal nimpa data ing file sing ditemtokake.

Ing kaloro kasus kasebut, file digawe yen ora ana.

Tulis menyang File Anyar

file = open('writefile.txt', 'w') file.write('Write some content!') file.close()

Output:

writefile.txt digawe karo isine:


Write some content! Cathetan:Yen file ora ana, file bakal digawe. Yen ana file, isi file bakal ditimpa!

Nambah Konten menyang File sing Ana

Kanggo nambah konten menyang file sing ana, kita kudu ngirim ing 'a' paramèter kanggo open() cara kanggo mode tambahan.

file = open('writefile.txt', 'a') file.write(' Write more content!') file.close()

Isinipun writefile.txt file:

Write some content! Write more content!

Cara Mbusak File ing Python

Kanggo mbusak file, kita kudu ngimpor os modul lan gunakake remove() cara:

import os if os.path.exists('writefile.txt'):
os.remove('writefile.txt')

Cara ing ndhuwur luwih dhisik mriksa manawa ana file sadurunge nyoba mbusak. Kesalahan diluncurake yen file ora ana.