簡體   English   中英

Python檢查目錄中具有特定名稱的所有文件

[英]Python check all file with a specific name in a directory

我在目錄( path = 'C://sample' )中具有三個或更多后綴(“ .txt”,“ .shp”,“ .shx”,“ .dbf”)的文件名( mytest. )。 我希望列出所有具有相同名稱的文件

我知道使用import glob可以列出具有特定后綴的所有文件

我的問題是如何在目錄中列出所有“ mytest”

ex 

mytest.txt
mytest.shp
mytest.bdf
mytest.shx

mylist = ["mytest.txt","mytest.shp","mytest.bdf","mytest.shx"]


mytest.txt
mytest.shp
mytest.bdf
mytest.shx
mytest.pjr

mylist = ["mytest.txt","mytest.shp","mytest.bdf","mytest.shx","mytest.pjr"]

正如您在問題中所說,您正在尋找glob模塊 ,但擴展名上帶有通配符:

import glob
glob.glob("mytest.*")

例:

$ ls
a.doc  a.pdf  a.txt  b.doc

$ python
Python 2.7.3 (default, Dec 18 2012, 13:50:09) [...]
>>> import glob
>>> glob.glob("a.*")
['a.doc', 'a.pdf', 'a.txt']
>>>

如果您還有其他名為mylist文件,這些文件沒有所需的擴展名,那么這可能是一個更好的解決方案:

import glob

extensions = ["txt","shp","bdf","shx"] # etc

mylist = list()
for ext in extensions:
    mylist += glob.glob("mylist.{}".format(ext))

甚至可能更容易:

mylist = [item for item in glob.glob('mylist.*') if item[-3:] in extensions]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM