Python gets file name using os.path lib

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

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

I want K without extension file

+4
source share
2 answers

I suggest you use the functions splitextand basenamefromos.path

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

See docs here .

+5
source

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
+4
source

Source: https://habr.com/ru/post/1621094/


All Articles