A Python, hi ha moltes funcions per llegir i escriure fitxers. Tant les funcions de lectura com d'escriptura funcionen amb fitxers oberts (fitxers oberts i enllaçats mitjançant un objecte fitxer). En aquesta secció, parlarem de les funcions d'escriptura per manipular les nostres dades mitjançant fitxers.
funció write().
La funció write() escriurà el contingut al fitxer sense afegir cap caràcter addicional.
Sintaxi :
# Writes string content referenced by file object. file_name.write(content)>
Segons la sintaxi, la cadena que es passa a la funció write() s'escriu al fitxer obert. La cadena pot incloure números, caràcters especials o símbols. Mentre escrivim dades en un fitxer, hem de saber que la funció d'escriptura no afegeix un caràcter de nova línia ( ) al final de la cadena. La funció write() retorna Cap.
Exemple:
Python 3
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.'>)> |
>
lexicogràficament
>
Sortida:
Data is written into the file.>
Execució de mostra:
Enter the name of the employee: Aditya Enter the name of the employee: Aditi Enter the name of the employee: Anil>
funció writelines().
Aquesta funció escriu el contingut d'una llista en un fitxer.
Sintaxi :
# write all the strings present in the list 'list_of_lines' # referenced by file object. file_name.writelines(list_of_lines)>
Segons la sintaxi, la llista de cadenes que es passa a la funció writelines() s'escriu al fitxer obert. De manera similar a la funció write(), la funció writelines() no afegeix un caràcter de nova línia ( ) al final de la cadena.
Exemple:
Python 3
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.'>)> |
>
java vs c++
>
Sortida:
Data is written into the file.>
Execució de mostra:
Enter the name of the employee: Rhea Enter the name of the employee: Rohan Enter the name of the employee: Rahul>
L'única diferència entre el escriure () i línies d'escriptura () és que write() s'utilitza per escriure una cadena en un fitxer ja obert mentre que el mètode writelines() s'utilitza per escriure una llista de cadenes en un fitxer obert.