Python’s built-inDocumentation Index
Fetch the complete documentation index at: https://mintlify.com/HotCode2025/Print-Estoy-Cansado-Jefe-TercerSemestre/llms.txt
Use this file to discover all available pages before exploring further.
open() function gives you direct access to the filesystem without any imports. What makes Python file handling distinctive is the context manager protocol: the with statement guarantees that a file handle is closed the moment the block exits — whether the code inside succeeds, raises an exception, or is interrupted. Relying on manual open() / close() pairs is fragile; relying on with is not.
open() accepts the file path, a mode string, and an optional encoding keyword. The mode controls whether Python opens the file for reading, writing, or both, and whether it expects text or raw bytes.'r''w''a''x'FileExistsError if the file already exists.'r+' / 'w+''b''r', 'w', etc.: 'rb', 'wb').'t''r', 'w', etc.).#Declaramos una variable
try:
archivo = open("prueba.txt", "w") # 'w' = write
archivo.write("Programamos con diferentes tipos de archivos, ahora en txt.\n")
archivo.write("Con esto terminamos")
except Exception as e:
print(e)
finally: # siempre se ejecuta
archivo.close() # Con esto se debe cerrar el archivo
Without an explicit
encoding argument, Python falls back to the platform default — cp1252 on Windows, UTF-8 on most Linux/macOS systems. This means the same script can produce or misread files differently across machines. Always specify encoding='utf8' when working with text files that may contain accented characters or non-ASCII symbols.# Declaramos una variable
try:
archivo = open('prueba.txt', 'w', encoding='utf8') # 'w' = write
archivo.write('Programamos con diferentes tipos de archivos, ahora en txt.\n')
archivo.write('Los acentos son importantes para las palabras\n')
archivo.write('como por ejemplo: acción, ejecución y producción\n')
archivo.write('Con esto terminamos')
except Exception as e:
print(e)
finally: # siempre se ejecuta
archivo.close() # Con esto se debe cerrar el archivo
# archivo.write('Todo quedo perfecto'): este es un error
archivo.read()archivo.read(n)n characters (advances the cursor)archivo.readline()\narchivo.readlines()for linea in archivo:archivo = open('prueba.txt', 'r', encoding='utf8')
# 'r' → read
# 'a' → append
# 'w' → write
# 'x' → raises exception if file exists
print(archivo.read())
archivo = open('prueba.txt', 'r',
encoding='utf8') # las letras son: 'r' read, 'a' append, 'w' write, 'x'
# print(archivo.read())
# print(archivo.read(16))
# print(archivo.read(10)) # Continuamos desde la línea anterior
# print(archivo.readline())
# print(archivo.readline())
# vamos a iterar el archivo, cada una de las líneas
# for linea in archivo:
# print(linea): iteramos todos los elementos del archivo
# print(archivo.readlines()[11]) # accedemos al archivo como si fuera una lista
# Anexamos información, copiamos a otro
archivo2 = open('copia.txt', 'a', encoding='utf8')
archivo2.write(archivo.read())
archivo.close() # cerramos el primer archivo
archivo2.close() # cerramos el segundo archivo
print('Se ha terminado el proceso de leer y copiar archivos')
Use
write() to insert a single string and chain multiple calls to build a file incrementally. Append mode ('a') is important when you want to add content without destroying what is already there.# Declaramos una variable
try:
archivo = open('prueba.txt', 'w', encoding='utf8') # 'w' truncates existing content
archivo.write('Programamos con diferentes tipos de archivos, ahora en txt.\n')
archivo.write('Los acentos son importantes para las palabras\n')
archivo.write('como por ejemplo: acción, ejecución y producción\n')
archivo.write('las letras son:\n')
archivo.write('r read leer,\n')
archivo.write('a append anexa,\n')
archivo.write('w write escribe,\n')
archivo.write('x crea un archivo\n')
archivo.write('t esta es para texto o text,\n')
archivo.write('b archivos binarios,\n')
archivo.write('w+ lee y escribe son igules r+\n')
archivo.write('Saludos a todos los alumnos de la tecnicatura\n')
archivo.write('Con esto terminamos\n')
except Exception as e:
print(e)
finally: # siempre se ejecuta
archivo.close() # Con esto se debe cerrar el archivo
When you need to add lines to a log file or a growing dataset, open it with
'a' instead of 'w'. Mode 'w' silently erases everything that was there before — a very easy mistake to make.The
with statement is Python’s built-in support for the context manager protocol. When the block exits (for any reason), Python automatically calls the file object’s __exit__ method, which closes the handle. You get exception safety for free with zero extra code.Always prefer
with open(...) over manual open() / close() pairs. Manual pairs require a try / finally to be safe — with gives you that guarantee in one clean line.# MANEJO DE CONTEXTO WITH: sintaxis simplificada, abre y cierra el archivo
with open('prueba.txt', 'r', encoding='utf8') as archivo:
print(archivo.read())
# No hace falta ni el try, ni el finally
# en el contexto de with lo que se ejecuta de manera automatica
# Utiliza diferentes metodos: __enter__ este es el que abre
# Ahora el siguiente metodo es el que cierra: __exit__
Under the hood,
with relies on two dunder methods. You can implement them yourself to wrap any resource:class ManejoArchivos:
def __init__(self, nombre):
self.nombre = nombre
def __enter__(self):
print('Obtenemos el recurso'.center(50, '-'))
self.nombre = open(self.nombre, 'r', encoding='utf8')
return self.nombre # returned value is bound to `as` variable
def __exit__(self, tipo_exception, valor_exception, traza_error):
print('cerramos el recurso'.center(50, '-'))
if self.nombre:
self.nombre.close() # Cerramos el archivo