Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use pathlib.Path.expanduser() and amend and use a PosixPath value?

Tags:

python

pathlib

Below shows how I obtained user1's home directory, create a new sub-directory name and create a new sub-directory there via python 3.6's os module.

>>> import os.path
>>> import os
>>> a = os.path.expanduser('~')
>>> a
'/home/user1'
>>> a_sub_dir = a + '/Sub_Dir_1'
>>> a_sub_dir
'/home/user1/Sub_Dir_1'
>>> def create_sub_dir( sub_dir ):
    try:
        os.makedirs( sub_dir, mode=0o777, exist_ok=False )
    except FileExistsError:
        print('Sub_directory already exist, no action taken.')
    else:
        print('Created sub_directory.')
>>> create_sub_dir( a_sub_dir )
Created sub_directory.
>>> create_sub_dir( a_sub_dir )
Sub_directory already exist, no action taken.

I would like to achieve the same as above via python 3.6's pathlib module. However, I can't seem to get it to work (see below). My questions:

  1. How do I use Path.expanduser()?
  2. How do I amend the info in a PosixPath(......) since it is not a string so that I can reuse it?
  3. I would like to amend the PosixPath and use it in my make_sub_dir() function. Will it work? Presently, I explicitly defined the new sub directory that i want to create to check that my make_sub_dir() function works.

Appreciate guidance on how to use pathlib. Thanks in advance.

>>> from pathlib import Path
>>> b = Path.expanduser('~')
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    b = Path.expanduser('~')
  File "/usr/lib/python3.6/pathlib.py", line 1438, in expanduser
    if (not (self._drv or self._root) and
AttributeError: 'str' object has no attribute '_drv'
>>> b = Path.expanduser('~/')
Traceback (most recent call last):
  File "<pyshell#88>", line 1, in <module>
    b = Path.expanduser('~/')
  File "/usr/lib/python3.6/pathlib.py", line 1438, in expanduser
    if (not (self._drv or self._root) and
AttributeError: 'str' object has no attribute '_drv'
>>> b = Path.home()
>>> b
PosixPath('/home/user1')
>>> b_sub_dir = b + '/Sub_Dir_1'
Traceback (most recent call last):
  File "<pyshell#91>", line 1, in <module>
    b_sub_dir = b + '/Sub_Dir_1'
TypeError: unsupported operand type(s) for +: 'PosixPath' and 'str'
>>> def make_sub_dir( sub_dir ):
    try:
        Path(sub_dir).mkdir(mode=0o777, parents=False, exist_ok=False)
    except FileNotFoundError:
        print('Parent directory do not exist, no action taken.')
    except FileExistsError:
        print('Sub_directory already exist, no action taken.')
    else:
        print('Created sub_directory.')
>>> make_sub_dir( '/home/user1/Sub_Dir_1' )
Sub_directory already exist, no action taken.
>>> make_sub_dir( '/home/user1/Sub_Dir_1' )
Created sub_directory.
>>> make_sub_dir( '/home/user1/Sub_Dir_1' )
Sub_directory already exist, no action taken.
like image 701
Sun Bear Avatar asked Jul 29 '19 07:07

Sun Bear


People also ask

What does Pathlib path () do?

As shown above, Pathlib creates a path to this file by putting this particular script in a Path object. Pathlib contains many objects such as PosixPath() and PurePath() , which we will learn more about in the following sections.

How do I change directory in Python Pathlib?

Python pathlib change directory We go inside another directory with os' chdir . #!/usr/bin/python from pathlib import Path from os import chdir path = Path('..') print(f'Current working directory: {path. cwd()}') chdir(path) print(f'Current working directory: {path. cwd()}') chdir('..')

What is path () in Python?

path module is a very extensively used module that is handy when processing files from different places in the system. It is used for different purposes such as for merging, normalizing and retrieving path names in python . All of these functions accept either only bytes or only string objects as their parameters.

What does Pathlib path return?

It returns the current working directory, that is, the directory from where you run the script. Oh I'm starting to see now. Looks like cwd is a bad way of establishing relative paths (like if I want to get to my excel file in the data directory).


1 Answers

pathlib's expanduser works differently than the one in os.path: it is applied to a Path object and takes no arguments. as shown in the doc you can either use:

>>> from pathlib import Path
>>> p = Path('~/films/Monty Python')
>>> p.expanduser()
PosixPath('/home/eric/films/Monty Python')

or work with .home():

>>> form pathlib import Path
>>> Path.home()
PosixPath('/home/antoine')

then in order to join directories you should use / (instead of +):

b_sub_dir = b / 'Sub_Dir_1'
like image 60
hiro protagonist Avatar answered Sep 28 '22 06:09

hiro protagonist