Karatu da Rubutun Fayiloli a ciki Python

A Python, don karantawa da rubuta fayiloli, muna amfani da ayyukan da aka tanadar a daidaitaccen ɗakin karatu da hanyoyin kamar,  da. Ga yadda ake sarrafa fayiloli a cikin: open() read() write() close() Python

 

Fayilolin Karatu

Don karanta fayil a cikin Python, muna amfani da aikin tare da yanayin "r"(karanta). Wannan aikin yana dawo da abun fayil, sannan zamu iya amfani da hanyoyi kamar karanta abun cikin fayil ɗin. open() read()

Misali :

# Read the content of a file  
with open("myfile.txt", "r") as file:  
    content = file.read()  
    print(content)  

 

Rubutun Fayiloli

Don rubuta zuwa fayil ko ƙirƙirar sabon fayil, muna amfani da aikin tare da yanayin "w"(rubuta). Idan fayil ɗin ya riga ya wanzu, za a sake rubuta shi, in ba haka ba, za a ƙirƙiri sabon fayil. open()

Misali :

# Write content to a file  
with open("output.txt", "w") as file:  
    file.write("This is the content written to the file.")  

 

Ajiye zuwa Fayiloli

Don haɗa abun ciki zuwa ƙarshen fayil ba tare da sake rubuta abubuwan da ke akwai ba, muna amfani da yanayin "a"(append).

Misali :

# Append content to a file  
with open("logfile.txt", "a") as file:  
    file.write("Appending this line to the file.")  

 

Rufe Fayiloli

Bayan karantawa ko rubutu, ana ba da shawarar rufe fayil ɗin ta amfani da close() hanyar. Koyaya, lokacin amfani da with bayanin, babu buƙatar rufe fayil ɗin da hannu kamar yadda Python zai rufe fayil ɗin ta atomatik lokacin fita daga with toshe.

 

Karatu da rubuta fayiloli a ciki yana Python ba ku damar aiki tare da bayanai daga fayiloli da ƙirƙirar aikace-aikacen da ke adanawa da sarrafa bayanai daga tushen waje.