Scrittura di file Python
Scrivi su un file esistente
Per scrivere su un file esistente, è necessario aggiungere un parametro alla
open()
funzione:
"a"
- Aggiungi: verrà aggiunto alla fine del file
"w"
- Scrivi: sovrascriverà qualsiasi contenuto esistente
Esempio
Apri il file "demofile2.txt" e aggiungi il contenuto al file:
f = open("demofile2.txt", "a")
f.write("Now the file has more content!")
f.close()
#open and read the file after the appending:
f =
open("demofile2.txt", "r")
print(f.read())
Esempio
Apri il file "demofile3.txt" e sovrascrivi il contenuto:
f = open("demofile3.txt", "w")
f.write("Woops! I have deleted the content!")
f.close()
#open and read the file after the appending:
f = open("demofile3.txt", "r")
print(f.read())
Nota: il metodo "w" sovrascriverà l'intero file.
Crea un nuovo file
Per creare un nuovo file in Python, usa il open()
metodo, con uno dei seguenti parametri:
"x"
- Crea - creerà un file, restituisce un errore se il file esiste
"a"
- Aggiungi - creerà un file se il file specificato non esiste
"w"
- Scrivi - creerà un file se il file specificato non esiste
Esempio
Crea un file chiamato "myfile.txt":
f = open("myfile.txt", "x")
Risultato: viene creato un nuovo file vuoto!
Esempio
Crea un nuovo file se non esiste:
f = open("myfile.txt", "w")