开发者

Find file in folder without knowing the extension?

Let's say I want to search for a file name "myfile" in a folder named "myfolder", how can I do it without knowing the format of the file? Another question: 开发者_如何学运维how to list all files of a folder and all the files of it's subfolders (and so on)? Thank you.


import os
import glob
 
path = 'myfolder/'
for infile in glob.glob( os.path.join(path, 'myfile.*') ):
    print "current file is: " + infile

if you want to list all the files in the folder, simply change the for loop into

for infile in glob.glob( os.path.join(path) ):


To list all files in a folder and its subfolders and so on, use the os.walk function:

import os
for root, dirs, files in os.walk('/blah/myfolder'):
    for name in files:
        if 'myfile' in name:
            print ("Found %s" % name)

In the easier case where you just want to look in 'myfolder' and not its subfolders, just use the os.listdir function:

import os
for name in os.listdir('/blah/myfolder'):
    if 'myfile' in name:
        print ("Found %s" % name)


The format (by which I mean you assume file type) is not related to its extension (which is part of its name).

If you're on a UNIX, you can use the find command. find myfolder -name myfile should work.

If you want a complete listing, you can either use find without any arguments, use ls with the -R option or use the tree command. All of these are on UNIX.


Also you can have a look to os.walk function if you want to look inside subdirectories.

http://docs.python.org/library/os.html#os.walk


I do not know the logic of python for this but I would do the following:

Loop through each file in the directory, get the names as strings and check to see if they begin with "myfile" by splitting the string on the "." you can compare what you are looking for with what you have.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜