Escritura de archivo de Python
Escribir en un archivo existente
Para escribir en un archivo existente, debe agregar un parámetro a la
open()
función:
"a"
- Agregar: se agregará al final del archivo
"w"
- Escribir: sobrescribirá cualquier contenido existente
Ejemplo
Abra el archivo "demofile2.txt" y agregue contenido al archivo:
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())
Ejemplo
Abra el archivo "demofile3.txt" y sobrescriba el contenido:
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: el método "w" sobrescribirá todo el archivo.
Crear un nuevo archivo
Para crear un nuevo archivo en Python, use el open()
método, con uno de los siguientes parámetros:
"x"
- Create - creará un archivo, devuelve un error si el archivo existe
"a"
- Agregar: creará un archivo si el archivo especificado no existe
"w"
- Escribir: creará un archivo si el archivo especificado no existe
Ejemplo
Cree un archivo llamado "myfile.txt":
f = open("myfile.txt", "x")
Resultado: ¡se crea un nuevo archivo vacío!
Ejemplo
Cree un nuevo archivo si no existe:
f = open("myfile.txt", "w")