5

Hello how can I get the file name with os.path lib? For example:

C:\Users\filippo\Desktop\K.java

I want the K without the extension file

Filippo
  • 163
  • 5
  • 13
  • 2
    [basename](https://docs.python.org/2/library/os.path.html#os.path.basename) + [splitext](https://docs.python.org/2/library/os.path.html#os.path.splitext)? – bereal Dec 21 '15 at 11:26

2 Answers2

6

I suggest you use the splitext and basename functions from os.path

K, ext = os.path.splitext(os.path.basename(my_path))

See the docs here.

qwattash
  • 855
  • 7
  • 14
4

You can achieve this using:

import os

filename = r"C:\Users\filippo\Desktop\K.java"

print os.path.splitext(filename)[0]
> C:\Users\filippo\Desktop\K

print os.path.splitext(filename)[1]
> .java

K, ext = os.path.splitext(os.path.basename(filename))
print K
print ext
> K
> .java
dot.Py
  • 5,007
  • 5
  • 31
  • 52