Reputation:
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
folder, name = '/'.join(file.split('/')[:-1]), file.split('/')[-1]
>>> 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
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