2017-08-29 81 views
-2

我正在寻找一个python脚本,该脚本可以在当前目录中找到此python脚本将从中运行的现有文件的确切文件名,该脚本可能会以增量方式命名。从python中的部分文件名中查找文件

例如该文件可能是: file1.dat file2.dat file3.dat ....

因此,我们知道的是,文件名的前缀file开始,我们知道,它与sufix .dat结束。

但我们不知道它是否会是file1.datfile1000.dat或其他任何东西。

所以我需要一个脚本来检查范围1-1000所有文件名从file1.datfile1000.dat,如果它发现目录中存在的文件名,它会返回一个成功消息。

+0

也许看看模块'glob' – PRMoureu

+0

看看这里:https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt-in -python – Dadep

+0

[在Python中查找扩展名为.txt的目录中的所有文件]的可能重复(https://stackoverflow.com/questions/3964681/find-all-files-in-a-directory-with-extension-txt -in-python) – Dadep

回答

1

试试这个:

for i in range(1, 1001): 
    if os.path.isfile("file{0}.dat".format(i)): 
     print("Success!") 
     break 
else: 
    print("Failure!") 
0

尝试是这样的:

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') 
+0

这有可能将文件与'file-sample.dat'或'file.dat'这样的名称进行匹配。 –

+0

@ZachGates是的,它的确如此。这只是一个起点。我100%确定他的命名规则是/将会是什么。 – LeopoldVonBuschLight

0

正如其他的评论,水珠等可供选择,但建议我个人认为listdir同时更舒适。

import os 
for file in os.listdir("/DIRECTORY"): 
    if file.endswith(".dat") and prefix in file: 
     print file 
+0

什么是'prefix'?我怀疑它是''file'',如果是这样的话,你可能会得到匹配的文件,比如'file-sample.dat'等等。使用'in'运算符,你甚至可以匹配像'sample-file .dat“或”ignore-this-file.dat“。 –

1

我会用Python的glob模块用正则表达式搜索。下面是一个示例表达式:

glob.glob(r'^file(\d+)\.dat$') 

这将匹配开始file一个文件名,其次是任何数字,并与.dat结束。有关这个正则表达式如何工作的更深入的解释,请查看Regex101,您也可以在其中进行测试。

注意:您的问题没有指定,但作为奖励,glob也支持递归搜索。

相关问题