Python Forum
file system path representation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
file system path representation
#3
(Feb-27-2021, 10:41 PM)Skaperen Wrote: why is a special function needed to get the "file system path representation" (how the documentation refers to it)? isn't the existing representation good enough? i'd like to see printed out what a representation that is not good enough looks like and what __fspath__() or os.fspath() would return. imagine you were the on implementing this function. what would the code look like?
So still on this wonder about this,did you read PEP 519👀
Short history in Python 3.4 we got pathlib.
>>> from pathlib import Path
>>> 
>>> working_dir = Path.cwd()
>>> working_dir
WindowsPath('C:/code')
>>> type(working_dir)
<class 'pathlib.WindowsPath'> 
So for various there is sometime a need to get string representation,as OS has the C's own decision to represent file system paths as string const char *.
So str() work,but has corner cases that may fail or create a file unwanted.
>>> working_dir
WindowsPath('C:/code')
>>> # Convert to string path
>>> new_path = str(working_dir)
>>> new_path
'C:\\code'
>>> type(new_path)
<class 'str'>
The preferred way is to use __fspath__() or os.fspath(),added in Python 3.6.
>>> working_dir
WindowsPath('C:/code')
>>> # Convert to string path
>>> working_dir.__fspath__()
'C:\\code'

>>> # Or 
>>> import os
>>> 
>>> os.fspath(working_dir)
'C:\\code
Reply


Messages In This Thread
file system path representation - by Skaperen - Feb-27-2021, 10:41 PM
RE: file system path representation - by snippsat - Feb-28-2021, 12:16 PM
RE: file system path representation - by Skaperen - Mar-01-2021, 02:42 AM
RE: file system path representation - by snippsat - Mar-01-2021, 10:53 AM
RE: file system path representation - by Skaperen - Mar-02-2021, 12:21 AM
RE: file system path representation - by snippsat - Mar-02-2021, 12:34 PM
RE: file system path representation - by Skaperen - Mar-03-2021, 02:12 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  importing a module given a path to the file Skaperen 8 1,388 Nov-04-2023, 07:03 PM
Last Post: Skaperen
  max component length of file path name Skaperen 1 1,107 Jun-19-2022, 04:03 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020