使用后缀检查文件的并行性

时间:2016-10-07 01:50:10

标签: python operating-system filepath file-extension suffix

给定文件目录,例如:

mydir/
  test1.abc
  set123.abc
  jaja98.abc
  test1.xyz
  set123.xyz
  jaja98.xyz

我需要检查每个.abc文件是否有等效的.xyz文件。我可以这样做:

>>> filenames = ['test1.abc', 'set123.abc', 'jaja98.abc', 'test1.xyz', 'set123.xyz', 'jaja98.xyz']
>>> suffixes = ('.abc', '.xyz')
>>> assert all( os.path.splitext(_filename)[0]+suffixes[1] in filenames for _filename in filenames if _filename.endswith(suffixes[0]) )

上面的代码应该传递断言,而这样的事情会失败:

>>> filenames = ['test1.abc', 'set123.abc', 'jaja98.abc', 'test1.xyz', 'set123.xyz']
>>> suffixes = ('.abc', '.xyz')                                                                                 >>> assert all(os.path.splitext(_filename)[0]+suffixes[1] in filenames for _filename in filenames if _filename.endswith(suffixes[0]))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError

但这有点过于冗长 是否有更好的做同样的检查?

1 个答案:

答案 0 :(得分:2)

您可以定义辅助函数,该函数将返回set个文件名而不包含与给定后缀匹配的扩展名。然后,您可以轻松检查带有后缀.abc的文件是带有后缀.xyz的文件的子集:

filenames = ['test1.abc', 'set123.abc', 'jaja98.abc', 'test1.xyz', 'set123.xyz', 'jaja98.xyz']
filenames2 = ['test1.abc', 'set123.abc', 'jaja98.abc', 'test1.xyz', 'set123.xyz']
suffixes = ('.abc', '.xyz')

def filter_ext(names, ext):
    return {n[:-len(ext)] for n in names if n.endswith(ext)}

assert filter_ext(filenames, suffixes[0]) <= filter_ext(filenames, suffixes[1])
assert filter_ext(filenames2, suffixes[0]) <= filter_ext(filenames2, suffixes[1]) # fail

以上方法也会更有效,因为它具有 O(n)时间复杂度,而原始 O(n ^ 2)。当然,如果列表很小,这并不重要。