user14185615
user14185615

Reputation:

Pythonic way to split Filepath into Folder and Filename

I have a string as follows

file = 'C:/folder/subfolder/data.csv'

And I'm looking for a Pythonic way to split this string into 2 variables: folder and name

Here is what I have so far

folder, name = '/'.join(file.split('/')[:-1]), file.split('/')[-1]

Output

>>> folder
'C:/folder/subfolder'
>>> name
'data.csv'

But the code is not so good, I think, because I had to repeat file.split('/') twice.
Is there a more Pythonic way like a list comprehension to do this?

Upvotes: 1

Views: 1541

Answers (1)

Tometzky
Tometzky

Reputation: 23920

In modern Python you should use pathlib:

file = pathlib.Path('C:/folder/subfolder/data.csv')
name = file.name
folder = str(file.parent)

Upvotes: 4

Related Questions