Cómo obtener una ruta de archivo absoluta en Python


Dada una ruta como "mydir/myfile.txt", ¿cómo encuentro la ruta de archivo absoluta relativa al directorio de trabajo actual en Python? Por ejemplo, en Windows, podría terminar con:

"C:/example/cwd/mydir/myfile.txt"
Author: Mechanical snail, 2008-09-09

9 answers

>>> import os
>>> os.path.abspath("mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'

También funciona si ya es una ruta absoluta:

>>> import os
>>> os.path.abspath("C:/example/cwd/mydir/myfile.txt")
'C:/example/cwd/mydir/myfile.txt'
 728
Author: sherbang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-24 22:23:56
>>> import os
>>> os.path.abspath('mydir/myfile.txt')
'C:\\example\\cwd\\mydir\\myfile.txt'
>>> 
 52
Author: Will Harris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-09 10:28:26

Podría usar la nueva biblioteca Python 3.4 pathlib. (También puede obtenerlo para Python 2.6 o 2.7 usando pip install pathlib.) Los autores escribieron: "El objetivo de esta biblioteca es proporcionar una jerarquía simple de clases para manejar las rutas del sistema de archivos y las operaciones comunes que los usuarios hacen sobre ellas."

Para obtener una ruta absoluta en Windows:

>>> from pathlib import Path
>>> p = Path("pythonw.exe").resolve()
>>> p
WindowsPath('C:/Python27/pythonw.exe')
>>> str(p)
'C:\\Python27\\pythonw.exe'

O en UNIX:

>>> from pathlib import Path
>>> p = Path("python3.4").resolve()
>>> p
PosixPath('/opt/python3/bin/python3.4')
>>> str(p)
'/opt/python3/bin/python3.4'

Los documentos están aquí: https://docs.python.org/3/library/pathlib.html

 52
Author: twasbrillig,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-30 16:30:10

Mejor aún, instale el path.py módulo, envuelve todas las funciones os.path y otras funciones relacionadas en métodos en un objeto que se pueden usar dondequiera que se usen cadenas:

>>> from path import path
>>> path('mydir/myfile.txt').abspath()
'C:\\example\\cwd\\mydir\\myfile.txt'
>>>
 23
Author: Tom,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2008-09-12 06:53:25

Hoy también puede usar el paquete unipath que se basó en path.py: http://sluggo.scrapping.cc/python/unipath /

>>> from unipath import Path
>>> absolute_path = Path('mydir/myfile.txt').absolute()
Path('C:\\example\\cwd\\mydir\\myfile.txt')
>>> str(absolute_path)
C:\\example\\cwd\\mydir\\myfile.txt
>>>

Recomendaría usar este paquete ya que ofrece una interfaz limpia para el sistema operativo común.path utilities .

 12
Author: Rudolf Olah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-10 17:20:08

Prefiero usar glob

Aquí es cómo listar todos los tipos de archivos en su carpeta actual:

import glob
for x in glob.glob():
    print(x)

Aquí es cómo listar todos (por ejemplo) .archivos txt en su carpeta actual:

import glob
for x in glob.glob('*.txt'):
    print(x)

Aquí es cómo listar todos los tipos de archivos en un directorio elegido:

import glob
for x in glob.glob('C:/example/hi/hello/'):
    print(x)

Espero que esto te haya ayudado

 3
Author: F. Taylor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-08-07 10:14:40

Si está en un mac

import os
upload_folder = os.path.abspath("static/img/users")

Esto te dará un camino completo:

print(upload_folder)

Mostrará la siguiente ruta:

>>>/Users/myUsername/PycharmProjects/OBS/static/img/user
 0
Author: chikwapuro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-03 21:12:44

En caso de que alguien esté usando python y linux y esté buscando la ruta completa al archivo:

>>> path=os.popen("readlink -f file").read()
>>> print path
abs/path/to/file
 0
Author: BND,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-04 19:09:56
filePath = os.path.abspath(directoryName)
filePathWithSlash = filePath + "\\"
filenameWithPath = os.path.join(filePathWithSlash, filename)
 -1
Author: frank__aguirre,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-30 08:46:34