Differenza tra la funzione write() e writelines() in Python

In Python ci sono molte funzioni per leggere e scrivere file. Sia le funzioni di lettura che quelle di scrittura funzionano su file aperti (file aperti e collegati tramite un oggetto file). In questa sezione discuteremo delle funzioni di scrittura per manipolare i nostri dati attraverso i file.

funzione write()

La funzione write() scriverà il contenuto nel file senza aggiungere caratteri aggiuntivi.

Sintassi :

# Writes string content referenced by file object. file_name.write(content) 

Secondo la sintassi, la stringa che viene passata alla funzione write() viene scritta nel file aperto. La stringa può includere numeri, caratteri speciali o simboli. Durante la scrittura dei dati in un file, dobbiamo sapere che la funzione di scrittura non aggiunge un carattere di nuova riga ( ) alla fine della stringa. La funzione write() restituisce None.

Esempio:

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.'> )>

Produzione:

Data is written into the file. 

Esecuzione del campione:

Enter the name of the employee: Aditya Enter the name of the employee: Aditi Enter the name of the employee: Anil 

funzione writelines()

Questa funzione scrive il contenuto di un elenco in un file.

Sintassi :

# write all the strings present in the list 'list_of_lines' # referenced by file object. file_name.writelines(list_of_lines) 

Secondo la sintassi, l'elenco di stringhe passato alla funzione writelines() viene scritto nel file aperto. Similmente alla funzione write(), la funzione writelines() non aggiunge un carattere di nuova riga ( ) alla fine della stringa.

Esempio:

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.'> )>

Produzione:

Data is written into the file. 

Esecuzione del campione:

Enter the name of the employee: Rhea Enter the name of the employee: Rohan Enter the name of the employee: Rahul 

L'unica differenza tra il scrivere() E righe di scrittura() è che write() viene utilizzato per scrivere una stringa in un file già aperto mentre il metodo writelines() viene utilizzato per scrivere un elenco di stringhe in un file aperto.