V Pythone existuje veľa funkcií na čítanie a zápis súborov. Funkcie čítania aj zápisu fungujú na otvorených súboroch (súbory otvorené a prepojené cez objekt súboru). V tejto časti budeme diskutovať o funkciách zápisu na manipuláciu s našimi údajmi prostredníctvom súborov.
funkcia write().
Funkcia write() zapíše obsah súboru bez pridania ďalších znakov.
Syntax :
# Writes string content referenced by file object. file_name.write(content)>
Podľa syntaxe sa reťazec odovzdaný funkcii write() zapíše do otvoreného súboru. Reťazec môže obsahovať čísla, špeciálne znaky alebo symboly. Pri zapisovaní údajov do súboru musíme vedieť, že funkcia write nepridáva na koniec reťazca znak nového riadku ( ). Funkcia write() vráti None.
Príklad:
Python3
pole vs zoznam polí
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.'>)> |
>
>
Výkon:
Data is written into the file.>
Ukážka behu:
podreťazec java
Enter the name of the employee: Aditya Enter the name of the employee: Aditi Enter the name of the employee: Anil>
funkcia writelines().
Táto funkcia zapíše obsah zoznamu do súboru.
Syntax :
# write all the strings present in the list 'list_of_lines' # referenced by file object. file_name.writelines(list_of_lines)>
Podľa syntaxe sa do otvoreného súboru zapíše zoznam reťazcov, ktoré sa odovzdajú funkcii writelines(). Podobne ako funkcia write() funkcia writelines() nepridáva znak nového riadku ( ) na koniec reťazca.
Príklad:
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.'>)> |
>
>
Výkon:
strojopis dátum čas
Data is written into the file.>
Ukážka behu:
Enter the name of the employee: Rhea Enter the name of the employee: Rohan Enter the name of the employee: Rahul>
Jediný rozdiel medzi písať () a writelines() je, že write() sa používa na zápis reťazca do už otvoreného súboru, zatiaľ čo metóda writelines() sa používa na zápis zoznamu reťazcov do otvoreného súboru.