2

I'm currently working with tkinter in Python (beginner), and I'm writing a small applet that requires one of the labels to dynamically change based on what the name of a selected .csv file is, without the '.csv' tag.

I can currently get the filepath to the .csv file using askopenfilename(), which returns a string that looks something like "User/Folder1/.../filename.csv". I need some way to extract "filename" from this filepath string, and I'm a bit stuck on how to do it. Is this simply a regex problem? Or is there a way to do this using string indices? Which is the "better" way to do it? Any help would be great. Thank you.

EDIT: The reason I was wondering if regex is the right way to do it is because there could be duplicates, e.g. if the user had something like "User/Folder1/hello/hello.csv". That's why I was thinking maybe just use string indices, since the file name I need will always end at [:-4]. Am I thinking about this the right way?

Axioms
  • 505
  • 2
  • 4
  • 11

1 Answers1

2

Solution:

import os
file = open('/some/path/to/a/test.csv')
fname = os.path.splitext(str(file))[0].split('/')[-1]
print(fname)

# test

If you get file path and name as string, then:

import os
file = "User/Folder1/test/filename.csv"
fname = os.path.splitext(file)[0].split('/')[-1]
print(fname)

# filename

Explanation on how it works:

Pay attention that command is os.path.splitEXT, not os.path.splitTEXT - very common mistake.

The command takes argument of type string, so if we use file = open(...), then we need to pass os.path.splitext argument of type string. Therefore in our first scenario we use:

str(file)

Now, this command splits complete file path + name string into two parts:

os.path.splitext(str(file))

# result:
['/some/path/to/a/test','csv']

In our case we only need first part, so we take it by specifying list index:

os.path.splitext(str(file))[0]

# result: 
'/some/path/to/a/test'

Now, since we only need file name and not the whole path, we split it by /:

os.path.splitext(str(file))[0].split('/')

# result:
['some','path','to','a','test']

And out of this we only need one last element, or in other words, first from the end:

os.path.splitext(str(file)[0].split('/')[-1]

Hope this helps.

Check for more here: Extract file name from path, no matter what the os/path format

Denis Rasulev
  • 3,744
  • 4
  • 33
  • 47