michaelg
michaelg

Reputation: 243

Removing file extension from filename with file handle as input

I have the following code f = open('01-01-2017.csv')

From f variable, I need to remove the ".csv" and set the remaining "01-01-2017" to a variable called "date". what is the best way to accomplish this

Upvotes: 1

Views: 2928

Answers (1)

Jean-François Fabre
Jean-François Fabre

Reputation: 140256

just retrieve the name of the file using f.name and apply os.path.splitext, keep the left part:

import os
date = os.path.splitext(os.path.basename(f.name))[0]

(I've used os.path.basename in case the file has an absolute path)

Upvotes: 2

Related Questions