Come aggiungere testo ad un file in Python
-
file.writeper aggiungere testo ad un file con modalitàa -
Aggiungere il parametro opzionale
filealla funzioneprintin Python 3 - Aggiungere una nuova riga nell’aggiunta di testo ad un file
Questo articolo di tutorial introdurrà come aggiungere testo ad un file in Python.
file.write per aggiungere testo ad un file con modalità a
Si può aprire il file in modalità a o a+ se si vuole aggiungere del testo ad un file.
destFile = r"temp.txt"
with open(destFile, "a") as f:
f.write("some appended text")
Il codice sopra riportato aggiunge il testo some appended text accanto all’ultimo carattere del file. Per esempio, se il file termina con this is the last sentence, allora diventa this is the last sentencesome appended text dopo l’aggiunta.
Creerà il file se il file non esiste nel percorso dato.
Aggiungere il parametro opzionale file alla funzione print in Python 3
In Python 3, è possibile “stampare” il testo sul file con il parametro opzionale file abilitato.
destFile = r"temp.txt"
Result = "test"
with open(destFile, "a") as f:
print("The result will be {}".format(Result), file=f)
Aggiungere una nuova riga nell’aggiunta di testo ad un file
Se si preferisce aggiungere il testo nella nuova riga, è necessario aggiungere la pausa del carrello \r\n dopo il testo aggiunto per garantire che il prossimo testo aggiunto verrà aggiunto nella nuova riga.
destFile = r"temp.txt"
with open(destFile, "a") as f:
f.write("the first appended text\r\n")
f.write("the second appended text\r\n")
f.write("the third appended text\r\n")
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn Facebook