odom0905
odom0905

Reputation: 25

how to split out the file name from path by different characters in python?

there:

I got a list of absolute path + file name by using glob.glob() function. However, I try to use split function to extract my file name but I can't find the best way. For example:

first item in my list is: 'C:\Users\xxxxx\Desktop\Python Training\Python Training-Home\Practices\Image Assembly\bird_01.png'. There are several images like bird_02.png...etc. I successfully resized them and tried to re-save them in different location. Please see below for part of my code. My problem statement is I can't find the way to extract "image_filename" in my code. I just need like bird_01, bird_02...etc. Please help me. Thank you in advance.

if not os.path.exists(output_dir):
os.mkdir(output_dir)
for image_file in all_image_files:
    print 'Processing', image_file, '...'
    img = Image.open(image_file)
    width, height =  img.size
    percent = float((float(basewidth)/float(width)))
    hresize = int(float(height) * float(percent))
    if width != basewidth:
        img = img.resize((basewidth, hresize), Image.ANTIALIAS) 
    image_filename = image_file.split('_')[0]
    image_filename = output_dir + '/' + image_filename
    print 'Save to ' + image_filename
    img.save(image_filename) 

Upvotes: 0

Views: 9733

Answers (2)

erickrf
erickrf

Reputation: 2104

In order to extract the name of the file, without the directory, use os.path.basename():

>>> path = r'c:\dir1\dir2\file_01.png'
>>> os.path.basename(path)
'file_01.png'

In your case, you might also want to use rsplit instead of split and limit to one split:

>>> name = 'this_name_01.png'
>>> name.split('_')
['this', 'name', '01.png']
>>> name.rsplit('_', 1)
['this_name', '01.png']

Upvotes: 2

cs95
cs95

Reputation: 403120

You can use the os.path.split function to extract the last part of your path:

>>> import os
>>> _, tail = os.path.split("/tmp/d/file.dat") 
>>> tail
'file.dat'

If you want only the filename without the extension, a safe way to do this is with os.path.splitext:

>>> os.path.splitext(tail)[0]
'file'

Upvotes: 3

Related Questions