0

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) 
1
  • There's a lot of image processing code that is not relevant to the problem and makes it harder to understand. Try to be more succinct about your issue :) Commented Jun 25, 2017 at 5:06

2 Answers 2

3

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'
Sign up to request clarification or add additional context in comments.

Comments

2

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']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.