如何使用Python检查basename(只是名称的一部分)文件存在?

时间:2021-02-10 21:22:22

I think the title explains it all. I need to check existence for a file that contains the word data in its name. I tried something like that os.path.exists(/d/prog/*data.txt) but that doesn't work.

我认为标题解释了这一切。我需要检查其名称中包含单词data的文件是否存在。我试过像os.path.exists(/d/prog/*data.txt)这样的东西,但这不起作用。

3 个解决方案

#1


Try glob for it:

尝试使用glob:

from glob import glob
if glob('/d/prog/*data.txt'):
    # blah blah 

#2


If you are on Windows:

如果你在Windows上:

>>> import glob
>>> glob.glob('D:\\test\\*data*')
['D:\\test\\data.1028.txt', 'D:\\test\\data2.1041.txt']

#3


You can't just do it with os.path.exists -- it expects full pathname. If do not know exact filename, you should first find this file on filesystem (and when you do, it proves that file exists).

你不能只用os.path.exists做它 - 它需要完整的路径名。如果不知道确切的文件名,你应该首先在文件系统上找到这个文件(当你这样做时,它证明文件存在)。

One option is to list directory (-ies), and find file manually:

一个选项是列出目录(-ies),并手动查找文件:

>>> import os
>>> file_list = os.listdir('/etc')
>>> [fn for fn in file_list if 'deny' in fn]
['hostapd.deny', 'at.deny', 'cron.deny', 'hosts.deny']

Another and more flexible option is to use glob.glob, which allows to use wildcards such as *, ? and [...]:

另一个更灵活的选择是使用glob.glob,它允许使用* ,?等通配符。和[...]:

>>> import glob
>>> glob.glob('/etc/*deny*')
['/etc/hostapd.deny', '/etc/at.deny', '/etc/cron.deny', '/etc/hosts.deny']

#1


Try glob for it:

尝试使用glob:

from glob import glob
if glob('/d/prog/*data.txt'):
    # blah blah 

#2


If you are on Windows:

如果你在Windows上:

>>> import glob
>>> glob.glob('D:\\test\\*data*')
['D:\\test\\data.1028.txt', 'D:\\test\\data2.1041.txt']

#3


You can't just do it with os.path.exists -- it expects full pathname. If do not know exact filename, you should first find this file on filesystem (and when you do, it proves that file exists).

你不能只用os.path.exists做它 - 它需要完整的路径名。如果不知道确切的文件名,你应该首先在文件系统上找到这个文件(当你这样做时,它证明文件存在)。

One option is to list directory (-ies), and find file manually:

一个选项是列出目录(-ies),并手动查找文件:

>>> import os
>>> file_list = os.listdir('/etc')
>>> [fn for fn in file_list if 'deny' in fn]
['hostapd.deny', 'at.deny', 'cron.deny', 'hosts.deny']

Another and more flexible option is to use glob.glob, which allows to use wildcards such as *, ? and [...]:

另一个更灵活的选择是使用glob.glob,它允许使用* ,?等通配符。和[...]:

>>> import glob
>>> glob.glob('/etc/*deny*')
['/etc/hostapd.deny', '/etc/at.deny', '/etc/cron.deny', '/etc/hosts.deny']