简体   繁体   中英

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) 

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'

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM