Akarii
Akarii

Reputation: 31

Python filename from path with \

I have a list of paths that looks like this C:/Users/myuser/Documents/files\my_file_1.csv and I want to get the file name from that by doing this:

path=['C:/Users/myuser/Documents/files\my_file_1.csv','C:/Users/myuser/Documents/files\my_file_2.csv',...]

filename, file_extension = os.path.splitext(path[0])

and I always get 'C:/Users/myuser/Documents/files\my_file_1' I know it must be for the ' \ ' slash but I haven't been able to replace it. Can anyone give me an idea ?

Upvotes: 0

Views: 45

Answers (2)

bigbounty
bigbounty

Reputation: 17358

As you are using windows and if you are using python 3.4+

>>> from pathlib import PureWindowsPath
>>> path=['C:/Users/myuser/Documents/files\my_file_1.csv','C:/Users/myuser/Documents/files\my_file_2.csv']
>>> print([PureWindowsPath(i).name for i in path])
['my_file_1.csv', 'my_file_2.csv']

Upvotes: 0

Cory Kramer
Cory Kramer

Reputation: 117856

You can use os.path.basename to get just the filename without the full directory, then os.path.splitext to remove the file extension.

>>> import os
>>> [os.path.splitext(os.path.basename(i))[0] for i in path]
['my_file_1', 'my_file_2']

Or if you want the filename and extension, but no directories

>>> [os.path.basename(i) for i in path]
['my_file_1.csv', 'my_file_2.csv']

Upvotes: 5

Related Questions