Sumit Bisht
Sumit Bisht

Reputation: 1517

Unable to get a valid pathname from python os.path.abspath

I have the following string containing absolute directory of a file.

'D:\Sample\Project\testXcl\data.xlsx'

On passing this into os.path.abspath, I am getting the following result:

'D:\\Sample\\Project\testXcl\\data.xlsx'

This happens because TestXcl folder name is read as \t. Wrong path/error also appears if any file/folder name is starting with n, a, b, f, r, v, x.

Is there any other method to rectify this, or should I go about replacing the string with correct file delimiters ?

Upvotes: 2

Views: 981

Answers (2)

phihag
phihag

Reputation: 287865

When you specify the path name, either escape the backslashes or use a raw string literal:

p = 'D:\\Sample\\Project\\testXcl\\data.xlsx'
p = r'D:\Sample\Project\testXcl\data.xlsx'

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798686

Use a raw string literal instead.

filename = r'D:\Sample\Project\testXcl\data.xlsx'

Upvotes: 5

Related Questions