La librería os
Contents
La librería os
#
Una de las librerías más utilizadas en Python es os
. Esta permite interactuar con el sistema operativo (de allí su nombre), de tal manera que podemos crear, eliminar y mover archivos y directorios, entre otras cosas. Debido a que es una interface miscelánea para el sistema operativo, la librería os
es muy grande y tiene muchos métodos 1. En este tutorial, veremos algunos de los más útiles para trabajar con archivos y directorios.
Nota
En las salidas de este cuaderno las rutas de archivo corresponden al ambiente local desde el cual se ejecuta el programa. Por lo tanto, las salidas serán diferentes para tu computador.
El directorio de trabajo#
El directorio de trabajo es el directorio desde el cual se ejecuta el programa. Para ver cuál es el directorio de trabajo, podemos usar el método getcwd()
:
import os
print(os.getcwd())
E:\Proyectos\curso_python_extenso\tutoriales
Para cambiar el directorio de trabajo, podemos usar el método chdir()
:
os.chdir("../archivos/txt")
print(os.getcwd())
E:\Proyectos\curso_python_extenso\archivos\txt
Listar archivos y directorios#
Para listar los archivos y directorios de un directorio, podemos usar el método listdir()
:
print(os.listdir("../archivos/txt"))
['arreola.txt', 'ejemplo.txt', 'el_quijote.txt']
También podemos utilizar el método walk
en caso de que queramos revisar directorios y subdirectorios:
for root, dirs, files in os.walk("../_build/html"):
print(root)
print(dirs)
print(files)
../_build/html
['actividades', 'tutoriales', '_images', '_sources', '_sphinx_design_static', '_static']
['.buildinfo', 'genindex.html', 'index.html', 'infotec.html', 'objects.inv', 'references.html', 'search.html', 'searchindex.js']
../_build/html\actividades
[]
['1-configuracion.html', '10-actividadfinal.html', '2-sintaxis_variables.html', '3-listas.html', '4-iteraciones.html', '5-condicionales.html', '6-diccionarios.html', '7-funciones.html', '8-funciones2.html', '9-actividadintermedia.html']
../_build/html\tutoriales
[]
['1-instalarPython.html', '10-listas.html', '11-iteraciones.html', '12-condicionales.html', '13-ifelse.html', '13-plogicas.html', '14-condicionPertenencia.html', '15-ifelse.html', '16-listaseif.html', '17-diccionarios.html', '18-iterardiccio.html', '19-funcionesIntro.html', '2-terminal.html', '20-funciones_y_TryExcept.html', '20-input.html', '21-funciones_y_TryExcept.html', '22-retornarvalores.html', '23-funcionesLlamados.html', '24-argsykwargs.html', '25-importarmodulos.html', '25-modularfunciones.html', '26-importarmodulos.html', '26-modularfunciones.html', '27-archivos.html', '27-introObjetos.html', '28-clases.html', '28-os.html', '29-csv.html', '3-instalarVSCode.html', '30-pandasCSV.html', '31-json.html', '32-regex.html', '33-regexcont.html', '34-introObjetos.html', '35-clases.html', '4-Git.html', '5-Github.html', '6-python.html', '7-variables.html', '8-operadores.html', '9-operaciones_string.html']
../_build/html\_images
[]
['condicional.png', 'función_estructura.png', 'parametros.png', 'scratch.png']
../_build/html\_sources
['actividades', 'tutoriales']
['index.md', 'infotec.ipynb', 'infotec.md', 'references.ipynb', 'references.md']
../_build/html\_sources\actividades
[]
['1-configuracion.md', '10-actividadfinal.ipynb', '10-actividadfinal.md', '2-sintaxis_variables.md', '3-listas.md', '4-iteraciones.md', '5-condicionales.md', '6-diccionarios.md', '7-funciones.md', '8-funciones2.md', '9-actividadintermedia.ipynb', '9-actividadintermedia.md']
../_build/html\_sources\tutoriales
[]
['1-instalarPython.md', '10-listas.ipynb', '10-listas.md', '11-iteraciones.ipynb', '11-iteraciones.md', '12-condicionales.ipynb', '12-condicionales.md', '13-ifelse.ipynb', '13-ifelse.md', '13-plogicas.ipynb', '13-plogicas.md', '14-condicionPertenencia.ipynb', '14-condicionPertenencia.md', '15-ifelse.ipynb', '15-ifelse.md', '16-listaseif.ipynb', '16-listaseif.md', '17-diccionarios.ipynb', '17-diccionarios.md', '18-iterardiccio.ipynb', '18-iterardiccio.md', '19-funcionesIntro.ipynb', '19-funcionesIntro.md', '2-terminal.ipynb', '2-terminal.md', '20-funciones_y_TryExcept.ipynb', '20-funciones_y_TryExcept.md', '20-input.ipynb', '20-input.md', '21-funciones_y_TryExcept.ipynb', '21-funciones_y_TryExcept.md', '22-retornarvalores.ipynb', '22-retornarvalores.md', '23-funcionesLlamados.ipynb', '23-funcionesLlamados.md', '24-argsykwargs.ipynb', '24-argsykwargs.md', '25-importarmodulos.ipynb', '25-importarmodulos.md', '25-modularfunciones.ipynb', '25-modularfunciones.md', '26-importarmodulos.ipynb', '26-importarmodulos.md', '26-modularfunciones.ipynb', '26-modularfunciones.md', '27-archivos.ipynb', '27-archivos.md', '27-introObjetos.ipynb', '27-introObjetos.md', '28-clases.ipynb', '28-clases.md', '28-os.ipynb', '28-os.md', '29-csv.ipynb', '29-csv.md', '3-instalarVSCode.md', '30-pandasCSV.ipynb', '30-pandasCSV.md', '31-json.ipynb', '31-json.md', '32-regex.ipynb', '32-regex.md', '33-regexcont.ipynb', '33-regexcont.md', '34-introObjetos.ipynb', '34-introObjetos.md', '35-clases.ipynb', '35-clases.md', '4-Git.md', '5-Github.md', '6-python.ipynb', '6-python.md', '7-variables.ipynb', '7-variables.md', '8-operadores.ipynb', '8-operadores.md', '9-operaciones_string.ipynb', '9-operaciones_string.md']
../_build/html\_sphinx_design_static
[]
['design-style.b7bb847fb20b106c3d81b95245e65545.min.css', 'design-tabs.js']
../_build/html\_static
['images', 'imgs', 'locales', 'scripts', 'styles', 'vendor']
['basic.css', 'check-solid.svg', 'clipboard.min.js', 'copy-button.svg', 'copybutton.css', 'copybutton.js', 'copybutton_funcs.js', 'design-style.b7bb847fb20b106c3d81b95245e65545.min.css', 'design-tabs.js', 'doctools.js', 'documentation_options.js', 'file.png', 'jquery-3.5.1.js', 'jquery.js', 'language_data.js', 'logo.png', 'minus.png', 'mystnb.css', 'plus.png', 'pygments.css', 'sbt-webpack-macros.html', 'searchtools.js', 'sphinx-thebe.css', 'sphinx-thebe.js', 'togglebutton.css', 'togglebutton.js', 'underscore-1.13.1.js', 'underscore.js', 'webpack-macros.html']
../_build/html\_static\images
[]
['logo_binder.svg', 'logo_colab.png', 'logo_deepnote.svg', 'logo_jupyterhub.svg']
../_build/html\_static\imgs
[]
['condicional.png', 'función_estructura.png', 'logo.png', 'parametros.png', 'scratch.png']
../_build/html\_static\locales
['ar', 'bg', 'bn', 'ca', 'cs', 'da', 'de', 'el', 'eo', 'es', 'et', 'fi', 'fr', 'hr', 'id', 'it', 'iw', 'ja', 'ko', 'lt', 'lv', 'ml', 'mr', 'ms', 'nl', 'no', 'pl', 'pt', 'ro', 'ru', 'sk', 'sl', 'sr', 'sv', 'ta', 'te', 'tg', 'th', 'tl', 'tr', 'uk', 'ur', 'vi', 'zh_CN', 'zh_TW']
[]
../_build/html\_static\locales\ar
['LC_MESSAGES']
[]
../_build/html\_static\locales\ar\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\bg
['LC_MESSAGES']
[]
../_build/html\_static\locales\bg\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\bn
['LC_MESSAGES']
[]
../_build/html\_static\locales\bn\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\ca
['LC_MESSAGES']
[]
../_build/html\_static\locales\ca\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\cs
['LC_MESSAGES']
[]
../_build/html\_static\locales\cs\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\da
['LC_MESSAGES']
[]
../_build/html\_static\locales\da\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\de
['LC_MESSAGES']
[]
../_build/html\_static\locales\de\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\el
['LC_MESSAGES']
[]
../_build/html\_static\locales\el\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\eo
['LC_MESSAGES']
[]
../_build/html\_static\locales\eo\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\es
['LC_MESSAGES']
[]
../_build/html\_static\locales\es\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\et
['LC_MESSAGES']
[]
../_build/html\_static\locales\et\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\fi
['LC_MESSAGES']
[]
../_build/html\_static\locales\fi\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\fr
['LC_MESSAGES']
[]
../_build/html\_static\locales\fr\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\hr
['LC_MESSAGES']
[]
../_build/html\_static\locales\hr\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\id
['LC_MESSAGES']
[]
../_build/html\_static\locales\id\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\it
['LC_MESSAGES']
[]
../_build/html\_static\locales\it\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\iw
['LC_MESSAGES']
[]
../_build/html\_static\locales\iw\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\ja
['LC_MESSAGES']
[]
../_build/html\_static\locales\ja\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\ko
['LC_MESSAGES']
[]
../_build/html\_static\locales\ko\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\lt
['LC_MESSAGES']
[]
../_build/html\_static\locales\lt\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\lv
['LC_MESSAGES']
[]
../_build/html\_static\locales\lv\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\ml
['LC_MESSAGES']
[]
../_build/html\_static\locales\ml\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\mr
['LC_MESSAGES']
[]
../_build/html\_static\locales\mr\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\ms
['LC_MESSAGES']
[]
../_build/html\_static\locales\ms\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\nl
['LC_MESSAGES']
[]
../_build/html\_static\locales\nl\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\no
['LC_MESSAGES']
[]
../_build/html\_static\locales\no\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\pl
['LC_MESSAGES']
[]
../_build/html\_static\locales\pl\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\pt
['LC_MESSAGES']
[]
../_build/html\_static\locales\pt\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\ro
['LC_MESSAGES']
[]
../_build/html\_static\locales\ro\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\ru
['LC_MESSAGES']
[]
../_build/html\_static\locales\ru\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\sk
['LC_MESSAGES']
[]
../_build/html\_static\locales\sk\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\sl
['LC_MESSAGES']
[]
../_build/html\_static\locales\sl\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\sr
['LC_MESSAGES']
[]
../_build/html\_static\locales\sr\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\sv
['LC_MESSAGES']
[]
../_build/html\_static\locales\sv\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\ta
['LC_MESSAGES']
[]
../_build/html\_static\locales\ta\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\te
['LC_MESSAGES']
[]
../_build/html\_static\locales\te\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\tg
['LC_MESSAGES']
[]
../_build/html\_static\locales\tg\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\th
['LC_MESSAGES']
[]
../_build/html\_static\locales\th\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\tl
['LC_MESSAGES']
[]
../_build/html\_static\locales\tl\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\tr
['LC_MESSAGES']
[]
../_build/html\_static\locales\tr\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\uk
['LC_MESSAGES']
[]
../_build/html\_static\locales\uk\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\ur
['LC_MESSAGES']
[]
../_build/html\_static\locales\ur\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\vi
['LC_MESSAGES']
[]
../_build/html\_static\locales\vi\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\zh_CN
['LC_MESSAGES']
[]
../_build/html\_static\locales\zh_CN\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\locales\zh_TW
['LC_MESSAGES']
[]
../_build/html\_static\locales\zh_TW\LC_MESSAGES
[]
['booktheme.po']
../_build/html\_static\scripts
[]
['pydata-sphinx-theme.js', 'sphinx-book-theme.js', 'sphinx-book-theme.js.map']
../_build/html\_static\styles
[]
['pydata-sphinx-theme.css', 'sphinx-book-theme.css', 'theme.css']
../_build/html\_static\vendor
['fontawesome']
[]
../_build/html\_static\vendor\fontawesome
['5.13.0']
[]
../_build/html\_static\vendor\fontawesome\5.13.0
['css', 'webfonts']
['LICENSE.txt']
../_build/html\_static\vendor\fontawesome\5.13.0\css
[]
['all.min.css']
../_build/html\_static\vendor\fontawesome\5.13.0\webfonts
[]
['fa-brands-400.eot', 'fa-brands-400.svg', 'fa-brands-400.ttf', 'fa-brands-400.woff', 'fa-brands-400.woff2', 'fa-regular-400.eot', 'fa-regular-400.svg', 'fa-regular-400.ttf', 'fa-regular-400.woff', 'fa-regular-400.woff2', 'fa-solid-900.eot', 'fa-solid-900.svg', 'fa-solid-900.ttf', 'fa-solid-900.woff', 'fa-solid-900.woff2']
Crear y eliminar directorios#
Para crear un directorio, podemos usar el método mkdir()
:
os.mkdir("nuevo")
print(os.listdir())
['1-instalarPython.md', '10-listas.md', '11-iteraciones.md', '12-condicionales.md', '13-plogicas.md', '14-condicionPertenencia.md', '15-ifelse.md', '16-listaseif.md', '17-diccionarios.md', '18-iterardiccio.md', '19-funcionesIntro.md', '2-terminal.md', '20-input.md', '21-funciones_y_TryExcept.md', '22-retornarvalores.md', '23-funcionesLlamados.md', '24-argsykwargs.md', '25-importarmodulos.md', '26-modularfunciones.md', '27-archivos.md', '28-os.md', '29-csv.md', '3-instalarVSCode.md', '30-pandasCSV.md', '31-json.md', '32-regex.md', '33-regexcont.md', '34-introObjetos.md', '35-clases.md', '4-Git.md', '5-Github.md', '6-python.md', '7-variables.md', '8-operadores.md', '9-operaciones_string.md', 'biblio.py', 'biblioteca.py', 'busqueda.py', 'diccionario.csv', 'inventario.csv', 'nuevo', 'tmp2.py', '__pycache__']
Para eliminar un directorio, podemos usar el método rmdir()
:
os.rmdir("nuevo")
print(os.listdir())
['1-instalarPython.md', '10-listas.md', '11-iteraciones.md', '12-condicionales.md', '13-plogicas.md', '14-condicionPertenencia.md', '15-ifelse.md', '16-listaseif.md', '17-diccionarios.md', '18-iterardiccio.md', '19-funcionesIntro.md', '2-terminal.md', '20-input.md', '21-funciones_y_TryExcept.md', '22-retornarvalores.md', '23-funcionesLlamados.md', '24-argsykwargs.md', '25-importarmodulos.md', '26-modularfunciones.md', '27-archivos.md', '28-os.md', '29-csv.md', '3-instalarVSCode.md', '30-pandasCSV.md', '31-json.md', '32-regex.md', '33-regexcont.md', '34-introObjetos.md', '35-clases.md', '4-Git.md', '5-Github.md', '6-python.md', '7-variables.md', '8-operadores.md', '9-operaciones_string.md', 'biblio.py', 'biblioteca.py', 'busqueda.py', 'diccionario.csv', 'inventario.csv', 'tmp2.py', '__pycache__']
También podemos utilizar el método makedirs()
, el cual es sumamente útil cuando queremos crear directorios anidados:
os.makedirs("nuevo/nuevo2", exist_ok=True)
print(os.listdir())
['1-instalarPython.md', '10-listas.md', '11-iteraciones.md', '12-condicionales.md', '13-plogicas.md', '14-condicionPertenencia.md', '15-ifelse.md', '16-listaseif.md', '17-diccionarios.md', '18-iterardiccio.md', '19-funcionesIntro.md', '2-terminal.md', '20-input.md', '21-funciones_y_TryExcept.md', '22-retornarvalores.md', '23-funcionesLlamados.md', '24-argsykwargs.md', '25-importarmodulos.md', '26-modularfunciones.md', '27-archivos.md', '28-os.md', '29-csv.md', '3-instalarVSCode.md', '30-pandasCSV.md', '31-json.md', '32-regex.md', '33-regexcont.md', '34-introObjetos.md', '35-clases.md', '4-Git.md', '5-Github.md', '6-python.md', '7-variables.md', '8-operadores.md', '9-operaciones_string.md', 'biblio.py', 'biblioteca.py', 'busqueda.py', 'diccionario.csv', 'inventario.csv', 'nuevo', 'tmp2.py', '__pycache__']
El parámetro exist_ok
indica si se debe lanzar una excepción si el directorio ya existe. Si exist_ok
es True
, no se lanzará una excepción. Esto evita que debamos utilizar un bloque try-except
para manejar la excepción.
Para eliminar directorios anidados, podemos usar el método removedirs()
:
os.removedirs("nuevo/nuevo2")
print(os.listdir())
['1-instalarPython.md', '10-listas.md', '11-iteraciones.md', '12-condicionales.md', '13-plogicas.md', '14-condicionPertenencia.md', '15-ifelse.md', '16-listaseif.md', '17-diccionarios.md', '18-iterardiccio.md', '19-funcionesIntro.md', '2-terminal.md', '20-input.md', '21-funciones_y_TryExcept.md', '22-retornarvalores.md', '23-funcionesLlamados.md', '24-argsykwargs.md', '25-importarmodulos.md', '26-modularfunciones.md', '27-archivos.md', '28-os.md', '29-csv.md', '3-instalarVSCode.md', '30-pandasCSV.md', '31-json.md', '32-regex.md', '33-regexcont.md', '34-introObjetos.md', '35-clases.md', '4-Git.md', '5-Github.md', '6-python.md', '7-variables.md', '8-operadores.md', '9-operaciones_string.md', 'biblio.py', 'biblioteca.py', 'busqueda.py', 'diccionario.csv', 'inventario.csv', 'tmp2.py', '__pycache__']
Rutear archivos y directorios#
Para rutear archivos y directorios, podemos usar el método path.join()
:
print(os.path.join("nuevo", "nuevo2", "nuevo3"))
nuevo\nuevo2\nuevo3
Es una buena práctica utilizar este método para rutear archivos y directorios, ya que este método es independiente del sistema operativo. Por ejemplo, si queremos rutear el archivo ejemplo.txt
en el directorio nuevo
, podemos hacer lo siguiente:
print(os.path.join("nuevo", "ejemplo.txt"))
nuevo\ejemplo.txt
En general se desaconseja utilizar el método format
o la concatenación para crear la ruta de un archivo o directorio. En general un sistema operativo puede deducir si una ruta en Linux o MacOS está escrita con diagonales o con barras invertidas, pero esto no es así en Windows. os
hace que sea más seguro indicar la ruta y evitar las particularidades de un sistema operativo.
Obtener el nombre de un archivo#
Para obtener el nombre de un archivo, podemos usar el método path.basename()
:
print(os.path.basename("../archivos/txt/ejemplo.txt"))
ejemplo.txt
Obtener el directorio de un archivo#
Para obtener el directorio de un archivo, podemos usar el método path.dirname()
:
print(os.path.dirname("../archivos/txt/ejemplo.txt"))
../archivos/txt
Obtener el nombre y el directorio de un archivo#
Para obtener el nombre y el directorio de un archivo, podemos usar el método path.split()
:
print(os.path.split("../archivos/txt/ejemplo.txt"))
('../archivos/txt', 'ejemplo.txt')
Obtener la extensión de un archivo#
Para obtener la extensión de un archivo, podemos usar el método path.splitext()
:
print(os.path.splitext("../archivos/txt/ejemplo.txt"))
('../archivos/txt/ejemplo', '.txt')
Obtener el tamaño de un archivo#
Para obtener el tamaño de un archivo, podemos usar el método path.getsize()
:
print(os.path.getsize("../archivos/txt/ejemplo.txt"))
235
Obtener la fecha de creación de un archivo#
Para obtener la fecha de creación de un archivo, podemos usar el método path.getctime()
:
print(os.path.getctime("../archivos/txt/ejemplo.txt"))
1681865490.048676
Obtener la fecha de modificación de un archivo#
Para obtener la fecha de modificación de un archivo, podemos usar el método path.getmtime()
:
print(os.path.getmtime("../archivos/txt/ejemplo.txt"))
1681852887.547928
Obtener la fecha de acceso de un archivo#
Para obtener la fecha de acceso de un archivo, podemos usar el método path.getatime()
:
print(os.path.getatime("../archivos/txt/ejemplo.txt"))
1684274172.0294585
Conclusión#
En general, la librería os
facilita significativamente el trabajo con archivos y directorios independientemente de la plataforma. Esto es importante, ya que debemos programar teniendo en cuenta a los usuarios posibles de nuestro programa, quienes tendrán distintos sistemas operativos y distintas configuraciones. os
no resuelve todos los posibles problemas que surjan en la ejecución de nuestro programa, pero sí nos permite evitar algunos de los problemas más comunes.
Notas#
- 1
Para ver todos los métodos de la librería
os
, podemos ejecutardir(os)
. También puede ser útil consultar la documentación oficial de la librería: https://docs.python.org/3/library/os.html.