Skip to main content

Documentation Index

Fetch the complete documentation index at: https://mintlify.com/marioaje/Python/llms.txt

Use this file to discover all available pages before exploring further.

Working with files is a fundamental skill in any programming language. Whether you need to persist user data between program runs, process configuration files, generate reports, or read structured data from spreadsheets, Python’s built-in file I/O tools make the job straightforward. Python provides the open() built-in for basic file operations and the os module for file-system-level tasks like deleting files and managing directories — all without installing any third-party packages.

Opening and Reading Files

The simplest way to open a file is to call open() with the filename as its only argument. By default this opens the file in read mode ("r"). Calling .read() on the returned file object loads the entire contents as a string; passing an integer argument reads exactly that many characters.
semana4/archivos/abrirarchivo.py
variable = open("demo.txt")
print(variable.read())  # lee todo el documento

print("///////////////////////////")
# puedo leer, la cantidad de caractertes.
variable = open("demo.txt")
print(variable.read(5))
# caso cuando es externo
# variable = open("//120-210-002/demo.txt")
# print(variable.read(5))
You can also read a file line by line using .readline(), or iterate over every line with a for loop — the most memory-efficient approach for large files.
test/archivo.py
f = open("demofile.txt", "r")
print(f.read())

# Return the 5 first characters of the file:
f = open("demofile.txt", "r")
print(f.read(5))

f = open("demofile.txt", "r")
print(f.readline())

f = open("demofile.txt", "r")
print(f.readline())
print(f.readline())

f = open("demofile.txt", "r")
for x in f:
    print(x)

f = open("demofile.txt", "r")
print(f.readline())
f.close()
Always close a file after you are done with it by calling f.close(), or — better yet — use the with open(...) context manager. The with block closes the file automatically when its body exits, even if an exception is raised:
with open("demo.txt", "r") as f:
    contents = f.read()
# file is automatically closed here

File Modes

open() accepts an optional second argument — the mode — that controls what you can do with the file.
ModeNameBehaviour
"r"ReadOpens an existing file for reading. Raises FileNotFoundError if the file does not exist. This is the default.
"a"AppendOpens a file and writes at the end. Creates the file if it does not exist.
"w"WriteOpens a file and writes from the beginning, overwriting all existing content. Creates the file if it does not exist.
"x"CreateCreates a new file. Raises FileExistsError if the file already exists.
Opening a file with "w" (write) mode permanently overwrites all of its existing content the moment open() is called — even before you write anything. If you only want to add data without erasing what is already there, use "a" (append) mode instead.

Writing and Appending

Use the "a" mode to safely add content to the end of a file (creating it if necessary) and the "w" mode when you want to replace the file’s contents entirely. Always call .close() when you are done, or use with open(...).
semana4/archivos/archivocreador.py
# Permite que Python te cree un archivo
fileOpen = open("fileOpen.txt", "a")
fileOpen.write("Un nuevo texto desde python")
fileOpen.close()
# a= append
# w= write
# r= read

archivocrear = open("archivocrear.sql", "a")
archivocrear.write("select * from datos")
archivocrear.close()

fileOpen = open("demo.txt", "w")
fileOpen.write("Un nuevo texto desde python reescribiendo")
fileOpen.close()
The example above demonstrates three typical patterns:
  • Append ("a") to fileOpen.txt — adds the string to whatever is already there.
  • Append ("a") to archivocrear.sql — Python can write any extension, not just .txt.
  • Write ("w") to demo.txt — wipes the previous content and replaces it entirely.

Reading CSV Files

Comma-separated values (CSV) files are one of the most common formats for exchanging tabular data. Python’s standard csv module provides a csv.reader that automatically parses each row into a Python list, handling quoted fields and delimiters correctly. Combine csv.reader with the with open() context manager so the file is closed automatically once all rows have been processed.
semana4/archivos/leer.py
import csv

# demos= open("grupo.csv","r")
# print(demos)
with open("grupo.csv", newline='') as File:
    reader = csv.reader(File)
    for fila in reader:
        print(fila)
The newline='' argument in open() is recommended by Python’s documentation when working with the csv module. It ensures that universal newline translation is disabled so that the CSV reader can handle line endings inside quoted fields correctly.

Deleting Files

Use the os module to remove files from the file system. Always check that the file exists first with os.path.exists() to avoid an FileNotFoundError.
semana4/archivos/borrararchivo.py
import os

variable = "demo.txt"
if os.path.exists(variable):
    print("El archivo fue encontrado", variable)
    os.remove(variable)
    print("El archivo fue eliminado", variable)
else:
    print("no existe un archivo con ese nombre")
The logic is straightforward:
  1. os.path.exists(variable) returns True if the path points to an existing file (or directory).
  2. os.remove(variable) deletes the file permanently — there is no recycle bin.
  3. The else branch gives the user a clear message when the file is not found.

Creating and Removing Directories

The os module also lets you create and remove directories. os.mkdir() creates a single directory at the given path. Combine it with os.path.join() to build paths in a cross-platform way instead of hard-coding slashes.
test/folder.py
# Python program to explain os.mkdir() method

# importing os module
import os

# Directory
directory = "GeeksforGeeks"

# Parent Directory path
parent_dir = ""

# Path
path = os.path.join(parent_dir, directory)

# Create the directory 'GeeksForGeeks' in '/home/User/Documents'
os.mkdir(path)
print("Directory '% s' created" % directory)

# Directory
directory = "Geeks"

# Parent Directory path
parent_dir = ""

# mode
mode = 0o666

# Path
path = os.path.join(parent_dir, directory)

# Create the directory 'GeeksForGeeks' in '/home/User/Documents'
# with mode 0o666
os.mkdir(path, mode)
print("Directory '% s' created" % directory)
To remove an empty directory use os.rmdir("folder_name"). The directory must be empty; if it contains files or subdirectories, use shutil.rmtree() from the shutil standard-library module instead.
semana4/archivos/borrandocarpeta.py
import os
# os.rmdir("test")

os.mkdir("Creadocarpeta")
The commented-out line os.rmdir("test") shows the removal syntax. The active line demonstrates that os.mkdir() can also be called without a joined path when the target directory sits in the current working directory.

Build docs developers (and LLMs) love