从python中的部分文件名中查找文件
我正在寻找一个python脚本,该脚本可以在当前目录中找到此python脚本将从中运行的现有文件的确切文件名,该脚本可能会以增量方式命名。从python中的部分文件名中查找文件
例如该文件可能是: file1.dat
file2.dat
file3.dat
....
因此,我们知道的是,文件名的前缀file
开始,我们知道,它与sufix .dat
结束。
但我们不知道它是否会是file1.dat
或file1000.dat
或其他任何东西。
所以我需要一个脚本来检查范围1-1000
所有文件名从file1.dat
到file1000.dat
,如果它发现目录中存在的文件名,它会返回一个成功消息。
试试这个:
for i in range(1, 1001):
if os.path.isfile("file{0}.dat".format(i)):
print("Success!")
break
else:
print("Failure!")
尝试是这样的:
import os
path = os.path.dirname(os.path.realpath(__file__))
for f_name in os.listdir(path):
if f_name.startswith('file') and f_name.endswith('.dat'):
print('found a match')
这有可能将文件与'file-sample.dat'或'file.dat'这样的名称进行匹配。 –
@ZachGates是的,它的确如此。这只是一个起点。我100%确定他的命名规则是/将会是什么。 – LeopoldVonBuschLight
正如其他的评论,水珠等可供选择,但建议我个人认为listdir同时更舒适。
import os
for file in os.listdir("/DIRECTORY"):
if file.endswith(".dat") and prefix in file:
print file
什么是'prefix'?我怀疑它是''file'',如果是这样的话,你可能会得到匹配的文件,比如'file-sample.dat'等等。使用'in'运算符,你甚至可以匹配像'sample-file .dat“或”ignore-this-file.dat“。 –
也许看看模块'glob' – PRMoureu
看看这里:https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in -python – Dadep
[在Python中查找扩展名为.txt的目录中的所有文件]的可能重复(https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt -in-python) – Dadep