[英]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. 通过使用glob.glob()函数,我得到了绝对路径+文件名的列表。 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'. 我列表中的第一项是: “ C:\\ Users \\ xxxxx \\ Desktop \\ Python Training \\ Python Training-Home \\ Practices \\ Image Assembly \\ bird_01.png”。 There are several images like bird_02.png...etc.
有几张图片,例如bird_02.png ...等。 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.
我的问题陈述是我找不到在代码中提取“ image_filename”的方法。 I just need like bird_01, bird_02...etc.
我只需要bird_01,bird_02 ...等等。 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: 您可以使用
os.path.split
函数提取路径的最后一部分:
>>> 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
是一种安全的方法:
>>> os.path.splitext(tail)[0]
'file'
In order to extract the name of the file, without the directory, use os.path.basename()
: 为了提取没有目录的文件名,请使用
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: 在您的情况下,您可能还想使用
rsplit
而不是split
并限制为一个split:
>>> name = 'this_name_01.png'
>>> name.split('_')
['this', 'name', '01.png']
>>> name.rsplit('_', 1)
['this_name', '01.png']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.