Convert WindowsPath to String

mhemmy picture mhemmy · Oct 15, 2018 · Viewed 17.2k times · Source
redpath = os.path.realpath('.')              
thispath = os.path.realpath(redpath)        
fspec = glob.glob(redpath+'/*fits')
thispath = os.path.realpath(thispath+'/../../../..')
p = Path(thispath)
userinput = 'n'
while (userinput == 'n'):
   text_file = next(p.glob('**/*.fits'))
   print("Is this the correct file path?")
   print(text_file)
   userinput = input("y or n")

parent_dir = text_file.parent.resolve()
fspec = glob.glob(parent_dir+'/*fits')

I am getting the error

unsupported operand type(s) for +: 'WindowsPath' and 'str'

I think this is because I am trying to glob a Windows File Path when I need to glob a string. Is there a way that I can convert WindowsPath to string so that I can glob all the files into one list?

Answer

Giova picture Giova · Jun 16, 2019

As most other Python classes do, the WindowsPath class, from pathlib, implements a non-defaulted "dunder string" method (__str__). It turns out that the string representation returned by that method for that class is exactly the string representing the filesystem path you are looking for. Here an example:

from pathlib import Path

p = Path('E:\\x\\y\\z')
>>> WindowsPath('E:/x/y/z')

p.__str__()
>>> 'E:\\x\\y\\z'

str(p)
>>> 'E:\\x\\y\\z'

The str builtin function actually calls the "dunder string" method under the hood, so the results are exaclty the same. By the way, as you can easily guess calling directly the "dunder string" method avoids a level of indirection by resulting in faster execution time.

Here the results of the tests I've done on my laptop:

from timeit import timeit

timeit(lambda:str(p),number=10000000)
>>> 2.3293891000000713

timeit(lambda:p.__str__(),number=10000000)
>>> 1.3876856000000544

Even if calling the __str__ method may appear a bit uglier in the source code, as you saw above, it leads to faster runtimes.