Guías sobre temas de bases de datos y programación
open()
La función open()
se usa para abrir archivos almacenados. Devuelve el contenido del archivo como objeto python.
Sintaxis
open(file_name, mode)
Parámetros
file_name: este parámetro como su nombre indica, es el nombre de archivo que queremos abrir.
mode: este parámetro es una cadena que se utiliza para especificar el modo en que se abrirá el archivo. Las siguientes cadena son las operaciones que se pueden utilizar para activar un modo especifico:
Ejemplos
Para crear un archivo de texto llamado “archivo.txt”.
file = open("archivo.txt", "x")
Leer y escribir un archivo
file = open("archivo.txt", "w")
file.write("Aprendiendo a escribir en archivos con Python.")
file.close()
# leemos el archivo
file = open("archivo.txt")
print(file.read())
Agregar contenido al archivo
file = open("archivo.txt", "a")
file.write("Añadiendo más texto en el archivo")
file.close()
# leemos el archivo
file = open("archivo.txt")
print(file.read())