Python programoje yra daug failų skaitymo ir rašymo funkcijų. Tiek skaitymo, tiek rašymo funkcijos veikia su atidarytais failais (failais, atidarytais ir susietais per failo objektą). Šiame skyriuje aptarsime rašymo funkcijas, skirtas valdyti duomenis per failus.
Write() funkcija
Funkcija write() įrašys turinį į failą nepridėdamas jokių papildomų simbolių.
Sintaksė :
# Writes string content referenced by file object. file_name.write(content)>
Pagal sintaksę eilutė, kuri perduodama funkcijai write (), įrašoma į atidarytą failą. Eilutėje gali būti skaičių, specialiųjų simbolių arba simbolių. Rašydami duomenis į failą turime žinoti, kad rašymo funkcija eilutės pabaigoje neprideda naujos eilutės simbolio ( ). Funkcija write () grąžina Nėra.
Pavyzdys:
Python3
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.'>)> |
>
>
Išvestis:
Data is written into the file.>
Pavyzdžio vykdymas:
Enter the name of the employee: Aditya Enter the name of the employee: Aditi Enter the name of the employee: Anil>
writelines() funkcija
Ši funkcija įrašo sąrašo turinį į failą.
Sintaksė :
# write all the strings present in the list 'list_of_lines' # referenced by file object. file_name.writelines(list_of_lines)>
Pagal sintaksę eilučių, perduodamų funkcijai writelines() sąrašas įrašomas į atidarytą failą. Panašiai kaip ir funkcija write(), funkcija writelines() neprideda naujos eilutės simbolio ( ) į eilutės pabaigą.
žemėlapio mašinraštis
Pavyzdys:
Python3
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.'>)> |
>
>
Išvestis:
Data is written into the file.>
Pavyzdžio vykdymas:
Enter the name of the employee: Rhea Enter the name of the employee: Rohan Enter the name of the employee: Rahul>
Vienintelis skirtumas tarp rašyti () ir rašymo eilutės () yra tai, kad write () naudojamas rašyti eilutę į jau atidarytą failą, o metodas writelines () naudojamas įrašyti eilučių sąrašą atidarytame faile.