Python 在目录中搜索文件名
Python search for file name in directory
如何确认搜索到的文件是否存在,就像执行 bash 脚本一样:
ls -l SOURCE | egrep PART_OF_FILENAME
result: the complete file name found.
当我在 python 中得到结果时:
import os
PART_OF_FILENAME in os.listdir(SOURCE)
return False
三元运算符应该做的
import os
print('File found!' if PART_OF_FILENAME in os.listdir(SOURCE) else 'Not found')
由于 listdir
方法 returns 文件名列表,使用 in
将检查确切的指定文件名是否在列表中,而不是检查如果指定的文件名作为子字符串存在于列表中的任何元素中。
相反,您可以遍历列表中的每个元素并搜索给定的子字符串,如下所示:
def searchSubstringInList(list, substring):
for element in list:
if (substring in element):
return element
然后 searchSubstringInList(os.listdir(source), 'PART_OF_FILENAME')
会得到完整的文件名。
如何确认搜索到的文件是否存在,就像执行 bash 脚本一样:
ls -l SOURCE | egrep PART_OF_FILENAME
result: the complete file name found.
当我在 python 中得到结果时:
import os
PART_OF_FILENAME in os.listdir(SOURCE)
return False
三元运算符应该做的
import os
print('File found!' if PART_OF_FILENAME in os.listdir(SOURCE) else 'Not found')
由于 listdir
方法 returns 文件名列表,使用 in
将检查确切的指定文件名是否在列表中,而不是检查如果指定的文件名作为子字符串存在于列表中的任何元素中。
相反,您可以遍历列表中的每个元素并搜索给定的子字符串,如下所示:
def searchSubstringInList(list, substring):
for element in list:
if (substring in element):
return element
然后 searchSubstringInList(os.listdir(source), 'PART_OF_FILENAME')
会得到完整的文件名。