Programmā Python ir daudz funkciju failu lasīšanai un rakstīšanai. Gan lasīšanas, gan rakstīšanas funkcijas darbojas ar atvērtiem failiem (failiem, kas atvērti un saistīti ar faila objektu). Šajā sadaļā mēs apspriedīsim rakstīšanas funkcijas, lai apstrādātu mūsu datus, izmantojot failus.
rakstīšanas () funkcija
Funkcija write() ierakstīs faila saturu, nepievienojot nekādas papildu rakstzīmes.
Sintakse :
# Writes string content referenced by file object. file_name.write(content)>
Saskaņā ar sintaksi virkne, kas tiek nodota funkcijai write (), tiek ierakstīta atvērtajā failā. Virknē var būt skaitļi, speciālās rakstzīmes vai simboli. Rakstot datus failā, mums jāzina, ka rakstīšanas funkcija nepievieno jaunas rindiņas rakstzīmi ( ) virknes beigās. Funkcija write () atgriež Nav.
Piemērs:
Python3
string.valueof
file> => open>(>'Employees.txt'>,>'w'>)> > for> i>in> range>(>3>):> >name>=> input>(>'Enter the name of the employee: '>)> >file>.write(name)> >file>.write(>'
'>)> > file>.close()> > print>(>'Data is written into the file.'>)> |
>
>
Izvade:
Data is written into the file.>
Parauga palaišana:
Enter the name of the employee: Aditya Enter the name of the employee: Aditi Enter the name of the employee: Anil>
writelines() funkcija
Šī funkcija ieraksta saraksta saturu failā.
Sintakse :
# write all the strings present in the list 'list_of_lines' # referenced by file object. file_name.writelines(list_of_lines)>
Atbilstoši sintaksei virkņu saraksts, kas tiek nodots funkcijai writelines (), tiek ierakstīts atvērtajā failā. Līdzīgi kā rakstīšanas () funkcijai, funkcija writelines () nepievieno jaunas rindiņas rakstzīmi ( ) virknes beigās.
Piemērs:
Python3
pārvērst virkni par int java
file1>=> open>(>'Employees.txt'>,>'w'>)> lst>=> []> for> i>in> range>(>3>):> >name>=> input>(>'Enter the name of the employee: '>)> >lst.append(name>+> '
'>)> > file1.writelines(lst)> file1.close()> print>(>'Data is written into the file.'>)> |
>
>
Izvade:
Data is written into the file.>
Parauga palaišana:
Enter the name of the employee: Rhea Enter the name of the employee: Rohan Enter the name of the employee: Rahul>
Vienīgā atšķirība starp rakstīt () un rakstīšanas līnijas () ir tas, ka write () tiek izmantots, lai ierakstītu virkni jau atvērtā failā, savukārt metode writelines () tiek izmantota, lai atvērtā failā ierakstītu virkņu sarakstu.