我在不同的位置有两个文件:/tmp/helpers_image.tif 和 /tmp/outputs/helpers_image.qml。我想在扩展名之前比较他们的名字。
如何比较这两个文件夹中的文件?
如果这些文件在同一个文件夹中,我可以使用:
t1 = 'helpers_image.qml'
t1_list= t1.split('.')
t1_list[0] == t2_list[0]
...假设另一个列表将被称为 t2。
请您参考如下方法:
您应该使用 os.path.basename 函数来获取文件的名称,无论它们位于哪个文件夹中。给你:
import os
filename1 = os.path.basename('/tmp/helpers_image.tif') # returns 'helpers_image.tif'
filename2 = os.path.basename('/tmp/outputs/helpers_image.qml') # return 'helpers_image.qml'
# Thanks to Cyrbil for noticing a bug here
name1 = filename1.rsplit('.', 1)[0] # returns 'helpers_image'
name2 = filename2.rsplit('.', 1)[0] # return 'helpers_image'
if name1 == name2: # This is True for this exact case
# your logic here
另一种方式是suggested by Dunes :
name1 = os.path.basename(os.path.splitext('/tmp/helpers_image.tif')[0])
name2 = os.path.basename(os.path.splitext('/tmp/outputs/helpers_image.qml')[0])
