0

Hello I am trying to split a path into directory and filename, on Windows. I am using the os.path.basepath API to accomplish that on Windows, but I am getting this error.

I tried upgrading pip3 followed by os_sys module, but still getting this error. Anyone can help me understand what is going on with os.path.basepath on Windows 11?

I have exhausted google search and reading blogs over this, but nothing is working at this point.

Python 3.9.13 (tags/v3.9.13:6de2ca5, May 17 2022, 16:36:42) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os.path
>>> os.path.basepath("c:\node\text.txt") 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'ntpath' has no attribute 'basepath'
>>> 

2 Answers 2

1

Two items:

  1. if by 'basepath', you want the path, use dirname (if you want to parent directory of text.txt) or basename if you just want the filename.

  2. Use either \\ for windows paths or use a raw string.

i.e.

for dir:

import os

os.path.dirname("c:\\node\\text.txt")

for filename:

import os

os.path.basename("c:\\node\\text.txt")

or

for dir:

os.path.dirname(r'c:\node\text.txt')

for filename:

os.path.basename(r'c:\node\text.txt')

I apologize as I wasn't too clear on whether you want the dirname or filename.

Sign up to request clarification or add additional context in comments.

3 Comments

Nope. same error: >>> import os >>> os.path.basepath("c:\\node\\text.txt") Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'ntpath' has no attribute 'basepath' >>> os.path.basepath(r'c:\node\text.txt') Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: module 'ntpath' has no attribute 'basepath'
my bad. Should use dirname or basename
thanks for point that out, I have accepted your response.
0

Your Windows uses ntpath, read more information in os.path link
So, use this to get basename or dirname in your machine

import ntpath
ntpath.basename(r"c:\node\text.txt")
# result: text.txt

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.