V Pythonu existuje mnoho funkcí pro čtení a zápis souborů. Funkce čtení i zápisu fungují na otevřených souborech (soubory otevřené a propojené přes objekt souboru). V této části se budeme zabývat funkcemi zápisu pro manipulaci s našimi daty prostřednictvím souborů.
funkce write().
Funkce write() zapíše obsah do souboru bez přidání dalších znaků.
Syntax :
# Writes string content referenced by file object. file_name.write(content)>
Podle syntaxe se řetězec předaný funkci write() zapíše do otevřeného souboru. Řetězec může obsahovat čísla, speciální znaky nebo symboly. Při zápisu dat do souboru musíme vědět, že funkce write nepřidává znak nového řádku ( ) na konec řetězce. Funkce write() vrací None.
Příklad:
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.'>)> |
rajesh khanna
>
>
Výstup:
Data is written into the file.>
Ukázka běhu:
Enter the name of the employee: Aditya Enter the name of the employee: Aditi Enter the name of the employee: Anil>
funkce writelines().
Tato funkce zapíše obsah seznamu do souboru.
Syntax :
# write all the strings present in the list 'list_of_lines' # referenced by file object. file_name.writelines(list_of_lines)>
Podle syntaxe se do otevřeného souboru zapíše seznam řetězců, které jsou předány funkci writelines(). Podobně jako u funkce write() ani funkce writelines() nepřidává znak nového řádku ( ) na konec řetězce.
Pří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ýstup:
Data is written into the file.>
Ukázka běhu:
Enter the name of the employee: Rhea Enter the name of the employee: Rohan Enter the name of the employee: Rahul>
Jediný rozdíl mezi napsat() a writelines() je, že write() se používá k zápisu řetězce do již otevřeného souboru, zatímco metoda writelines() se používá k zápisu seznamu řetězců do otevřeného souboru.