Librería pathlib (paths orientadas a objetos)#
Última modificación: Mayo 13, 2022
Permite representar el path en el sistema de archivos del sistema operativo.
Tabla de equivalencias#
os & os.path pathlib
------------------------------------------------
os.mkdir() Path.mkdir()
os.makedirs() Path.mkdir()
os.rename() Path.rename()
os.replace() Path.replace()
os.rmdir() Path.rmdir()
os.remove() Path.unlink()
os.getcwd() Path.cwd()
os.path.exists() Path.exists()
os.listdir() Path.iterdir()
os.path.isdir() Path.is_dir()
os.path.isfile() Path.is_file()
os.path.join() PurePath.joinpath()
os.path.basename() PurePath.name()
os.path.dirname() PurePath.parent
os.path.splittext() PurePath.suffix
Importación#
[1]:
from pathlib import Path, PurePath, PureWindowsPath, PurePosixPath, PosixPath
Uso básico#
[2]:
#
# Subdirectorios
#
p = Path(".")
[x for x in p.iterdir() if x.is_dir()]
[2]:
[PosixPath('.ipynb_checkpoints'), PosixPath('assets')]
[3]:
#
# Listado de archivos de código fuente en el árbol de directorios
#
list(p.glob("**/*.ipynb"))
[3]:
[PosixPath('1-01_datetime.ipynb'),
PosixPath('1-02-re.ipynb'),
PosixPath('1-03_os.ipynb'),
PosixPath('1-04_glob.ipynb'),
PosixPath('1-05_collections.ipynb'),
PosixPath('1-06_logging.ipynb'),
PosixPath('1-07_ppring.ipynb'),
PosixPath('1-08_itertools.ipynb'),
PosixPath('1-09_pathlib.ipynb'),
PosixPath('.ipynb_checkpoints/1-01_datetime-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-02-re-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-03_os-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-04_glob-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-06_logging-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-07_ppring-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-08_itertools-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-09_pathlib-checkpoint.ipynb')]
[4]:
#
# Navegación
#
p = Path("/etc")
q = p / "init.d" / "reboot"
q
[4]:
PosixPath('/etc/init.d/reboot')
[5]:
q.resolve()
[5]:
PosixPath('/etc/init.d/reboot')
[6]:
#
# Existe?
#
q.exists()
[6]:
False
[7]:
#
# Es directorio?
#
q.is_dir()
[7]:
False
Pure paths#
[8]:
PurePath("setup.py")
[8]:
PurePosixPath('setup.py')
[9]:
PurePath("foo", "some/path", "bar")
[9]:
PurePosixPath('foo/some/path/bar')
[10]:
PurePath(
Path("foo"),
Path("bar"),
)
[10]:
PurePosixPath('foo/bar')
[11]:
PurePath()
[11]:
PurePosixPath('.')
[12]:
PurePath('/etc', '/usr', 'lib64')
[12]:
PurePosixPath('/usr/lib64')
[13]:
PureWindowsPath('c:/Windows', 'd:bar')
[13]:
PureWindowsPath('d:bar')
[14]:
PureWindowsPath('c:/Windows', '/Program Files')
[14]:
PureWindowsPath('c:/Program Files')
[15]:
PurePath('foo//bar')
[15]:
PurePosixPath('foo/bar')
[16]:
PurePath('foo/./bar')
[16]:
PurePosixPath('foo/bar')
[17]:
PurePath('foo/../bar')
[17]:
PurePosixPath('foo/../bar')
[18]:
PurePosixPath('/etc')
[18]:
PurePosixPath('/etc')
[19]:
PureWindowsPath('c:/Program Files/')
[19]:
PureWindowsPath('c:/Program Files')
Propiedades Generales#
[20]:
PurePosixPath('foo') == PurePosixPath('FOO')
[20]:
False
[21]:
PureWindowsPath('foo') == PureWindowsPath('FOO')
[21]:
True
[22]:
PureWindowsPath('FOO') in { PureWindowsPath('foo') }
[22]:
True
[23]:
PureWindowsPath('C:') < PureWindowsPath('d:')
[23]:
True
Operadores#
[24]:
p = PurePath('/etc')
p
[24]:
PurePosixPath('/etc')
[25]:
p / 'init.d' / 'apache2'
[25]:
PurePosixPath('/etc/init.d/apache2')
[26]:
q = PurePath('bin')
'/usr' / q
[26]:
PurePosixPath('/usr/bin')
[27]:
import os
p = PurePath('/etc')
os.fspath(p)
[27]:
'/etc'
[28]:
p = PurePath('/etc')
str(p)
[28]:
'/etc'
[29]:
p = PureWindowsPath('c:/Program Files')
str(p)
[29]:
'c:\\Program Files'
Acceso a partes individuales#
[30]:
PureWindowsPath('c:/Program Files/').drive
[30]:
'c:'
[31]:
PureWindowsPath('/Program Files/').drive
[31]:
''
[32]:
PurePosixPath('/etc').drive
[32]:
''
[33]:
PureWindowsPath('c:/Program Files/').root
[33]:
'\\'
[34]:
PureWindowsPath('c:Program Files/').root
[34]:
''
[35]:
PureWindowsPath('//host/share').root
[35]:
'\\'
[36]:
PureWindowsPath('c:/Program Files/').anchor
[36]:
'c:\\'
[37]:
PureWindowsPath('c:Program Files/').anchor
[37]:
'c:'
[38]:
PurePosixPath('/etc').anchor
[38]:
'/'
[39]:
PureWindowsPath('//host/share').anchor
[39]:
'\\\\host\\share\\'
[40]:
p = PureWindowsPath('c:/foo/bar/setup.py')
p.parents[0]
[40]:
PureWindowsPath('c:/foo/bar')
[41]:
p.parents[1]
[41]:
PureWindowsPath('c:/foo')
[42]:
p.parents[2]
[42]:
PureWindowsPath('c:/')
[43]:
p = PurePosixPath('/a/b/c/d')
p.parent
[43]:
PurePosixPath('/a/b/c')
[44]:
p = PurePosixPath('/')
p.parent
[44]:
PurePosixPath('/')
[45]:
p = PurePosixPath('.')
p.parent
[45]:
PurePosixPath('.')
[46]:
PurePosixPath('my/library/setup.py').name
[46]:
'setup.py'
[47]:
PureWindowsPath('//some/share/setup.py').name
[47]:
'setup.py'
[48]:
PureWindowsPath('//some/share').name
[48]:
''
[49]:
PurePosixPath('my/library/setup.py').suffix
[49]:
'.py'
[50]:
PurePosixPath('my/library.tar.gz').suffix
[50]:
'.gz'
[51]:
PurePosixPath('my/library').suffix
[51]:
''
[52]:
PurePosixPath('my/library.tar.gar').suffixes
[52]:
['.tar', '.gar']
[53]:
PurePosixPath('my/library.tar.gz').suffixes
[53]:
['.tar', '.gz']
[54]:
PurePosixPath('my/library').suffixes
[54]:
[]
[55]:
PurePosixPath('my/library.tar.gz').stem
[55]:
'library.tar'
[56]:
PurePosixPath('my/library.tar').stem
[56]:
'library'
[57]:
PurePosixPath('my/library').stem
[57]:
'library'
[58]:
PurePosixPath('/etc').joinpath('passwd')
[58]:
PurePosixPath('/etc/passwd')
[59]:
PurePosixPath('/etc').joinpath(PurePosixPath('passwd'))
[59]:
PurePosixPath('/etc/passwd')
[60]:
PurePosixPath('/etc').joinpath('init.d', 'apache2')
[60]:
PurePosixPath('/etc/init.d/apache2')
[61]:
PureWindowsPath('c:').joinpath('/Program Files')
[61]:
PureWindowsPath('c:/Program Files')
[62]:
PurePath('a/b.py').match('*.py')
[62]:
True
[63]:
PurePath('/a/b/c.py').match('b/*.py')
[63]:
True
[64]:
PurePath('/a/b/c.py').match('a/*.py')
[64]:
False
[65]:
PurePath('/a.py').match('/*.py')
[65]:
True
[66]:
PurePath('a/b.py').match('/*.py')
[66]:
False
Métodos#
[67]:
Path.cwd()
[67]:
PosixPath('/workspace/the_python_tutorial_10_brief_tour_of_the_standard_library')
[68]:
Path.home()
[68]:
PosixPath('/root')
[69]:
Path('.').exists()
[69]:
True
[70]:
Path('setup.py').exists()
[70]:
False
[71]:
Path('/etc').exists()
[71]:
True
[72]:
Path('nonexistentfile').exists()
[72]:
False
[73]:
p = PosixPath('~/films/Monty Python')
p.expanduser()
[73]:
PosixPath('/root/films/Monty Python')
[74]:
sorted(Path('.').glob('*.ipynb'))
[74]:
[PosixPath('1-01_datetime.ipynb'),
PosixPath('1-02-re.ipynb'),
PosixPath('1-03_os.ipynb'),
PosixPath('1-04_glob.ipynb'),
PosixPath('1-05_collections.ipynb'),
PosixPath('1-06_logging.ipynb'),
PosixPath('1-07_ppring.ipynb'),
PosixPath('1-08_itertools.ipynb'),
PosixPath('1-09_pathlib.ipynb')]
[75]:
sorted(Path('.').glob('*/*.ipynb'))
[75]:
[PosixPath('.ipynb_checkpoints/1-01_datetime-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-02-re-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-03_os-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-04_glob-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-06_logging-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-07_ppring-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-08_itertools-checkpoint.ipynb'),
PosixPath('.ipynb_checkpoints/1-09_pathlib-checkpoint.ipynb')]
[76]:
p = Path('.')
for child in p.iterdir():
print(child)
.DS_Store
.ipynb_checkpoints
1-01_datetime.ipynb
1-02-re.ipynb
1-03_os.ipynb
1-04_glob.ipynb
1-05_collections.ipynb
1-06_logging.ipynb
1-07_ppring.ipynb
1-08_itertools.ipynb
1-09_pathlib.ipynb
assets
bar
my_text_file
newfile
[77]:
p = Path('my_text_file')
p.write_text('Text file contents')
[77]:
18
[78]:
p.read_text()
[78]:
'Text file contents'
[79]:
p = Path('foo')
p.open('w').write('some text')
[79]:
9
[80]:
target = Path('bar')
p.rename(target)
[80]:
PosixPath('bar')
[81]:
target.open().read()
[81]:
'some text'
[82]:
Path('newfile').touch()
!ls n*
newfile