Choose a file starting with a given string

前端 未结 6 835
故里飘歌
故里飘歌 2020-12-13 12:38

In a directory I have a lot of files, named more or less like this:

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

In Python, I ha

相关标签:
6条回答
  • 2020-12-13 12:50
    import os, re
    for f in os.listdir('.'):
       if re.match('001_MN_DX', f):
           print f
    
    0 讨论(0)
  • 2020-12-13 12:57

    Try using os.listdir,os.path.join and os.path.isfile.
    In long form (with for loops),

    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)
    

    Code, with list-comprehensions is

    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]
    

    Check here for the long explanation...

    0 讨论(0)
  • 2020-12-13 13:06

    You can use the module glob, it follows the Unix shell rules for pattern matching. See more.

    from glob import glob
    
    files = glob('*001_MN_DX*')
    
    0 讨论(0)
  • 2020-12-13 13:07
    import os
    prefixed = [filename for filename in os.listdir('.') if filename.startswith("prefix")]
    
    0 讨论(0)
  • 2020-12-13 13:08

    You can use the os module to list the files in a directory.

    Eg: Find all files in the current directory where name starts with 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
    
    0 讨论(0)
  • 2020-12-13 13:10
    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
    
    0 讨论(0)
提交回复
热议问题