【问题标题】:Compare two filenames in different folders比较不同文件夹中的两个文件名
【发布时间】:2015-08-06 12:22:42
【问题描述】:

我在不同的位置有两个文件:/tmp/helpers_image.tif/tmp/outputs/helpers_image.qml。我想在扩展之前比较他们的名字。

如何比较这两个文件夹中的文件?

如果这些文件在同一个文件夹中,我可以使用:

t1 = 'helpers_image.qml'
t1_list= t1.split('.') 
t1_list[0] == t2_list[0]

...假设另一个列表将被称为t2

【问题讨论】:

    标签: python string split


    【解决方案1】:

    您应该使用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])
    

    【讨论】:

    • 您可能需要重新进行拆分,因为像 my.file.txt 这样的文件名将无法正常工作。 'my.file.txt'.rsplit('.', 1)[0]
    • 除了rsplit,还有os.path.splitext
    • os.path.splitext(path),确定吗?
    • 沙丘回答正常。但不要使用文件名,(+不要编码文件名使用目录)
    【解决方案2】:

    除此之外,如果你发现你需要匹配多个文件名,那么你可以使用集合。

    files1 = ['helpers_image1.qml', 'helpers_image2.qml', 'helpers_image3.qml', 'helpers_imag4.qml']
    files2 = ['helpers_image2.qml', 'helpers_image3.qml']
    print set(files1).intersection( set(files2) )
    

    输出:

    set(['helpers_image3.qml', 'helpers_image2.qml'])

    【讨论】:

    • "我想在扩展前比较他们的名字"
    • 糟糕,谢谢!那么 Cyrbil 的回答就好了。
    • 赞成回答错误的问题,这恰好是我目前的问题。诺斯!
    猜你喜欢
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-12
    • 1970-01-01
    • 2018-10-13
    相关资源
    最近更新 更多