簡體   English   中英

選擇以給定字符串開頭的文件

[英]Choose a file starting with a given string

在一個目錄中,我有很多文件,或多或少這樣命名:

001_MN_DX_1_M_32
001_MN_SX_1_M_33
012_BC_2_F_23
...
...

在 Python 中,我必須編寫一個代碼,從目錄中選擇一個以特定字符串開頭的文件。 例如,如果字符串是001_MN_DX ,則 Python 選擇第一個文件,依此類推。

我該怎么做?

import os
prefixed = [filename for filename in os.listdir('.') if filename.startswith("prefix")]

嘗試使用os.listdiros.path.joinos.path.isfile
長格式(帶有 for 循環),

import os
path = 'C:/'
files = []
for i in os.listdir(path):
    if os.path.isfile(os.path.join(path,i)) and '001_MN_DX' in i:
        files.append(i)

帶有列表推導式的代碼是

import os
path = 'C:/'
files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path,i)) and \
         '001_MN_DX' in i]

在這里查看詳細解釋...

您可以使用模塊glob ,它遵循 Unix shell 模式匹配規則。 查看更多。

from glob import glob

files = glob('*001_MN_DX*')
import os, re
for f in os.listdir('.'):
   if re.match('001_MN_DX', f):
       print f

您可以使用 os 模塊列出目錄中的文件。

例如:查找當前目錄中名稱以 001_MN_DX 開頭的所有文件

import os
list_of_files = os.listdir(os.getcwd()) #list of files in the current directory
for each_file in list_of_files:
    if each_file.startswith('001_MN_DX'):  #since its all type str you can simply use startswith
        print each_file

使用較新的pathlib模塊,請參閱鏈接

from pathlib import Path
myDir = Path('my_directory/')

fileNames = [file.name for file in myDir.iterdir() if file.name.startswith('prefix')]    
filePaths = [file for file in myDir.iterdir() if file.name.startswith('prefix')]
import os
 for filename in os.listdir('.'):
    if filename.startswith('criteria here'):
        print filename #print the name of the file to make sure it is what 
                               you really want. If it's not, review your criteria
                #Do stuff with that file

暫無
暫無

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

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