Python提取嵌套文件夹下指定文件操作源码,,如何在多重嵌套的文件夹内


如何在多重嵌套的文件夹内,提取到已知文件名的内容或是文件呢?本文就是关于Python提取嵌套文件夹下指定文件操作源码示例

版本:python2.6.6
环境:window xp

python代码编写思路:
首先,将两个py文件放在需要的文件夹下面,先运行filelist.py,在运行run.py。这两个文件的作用,分别如下:
filelist.py:
获取当前文件夹下面的文件列表,生成一个names.txt文件,可以手动修改这个文件,设置需要提取的文件列表。
run.py:
运行后提示需要输入目标文件夹,然后程序会自动根据names.txt将文件转移到指定目录下

filelist.py文件Python源码:

#encoding: utf-8import osfilenames = os.listdir(os.getcwd())for name in filenames:filenames[filenames.index(name)] = nameout = open('names.txt','w')for name in filenames:                filetype = name[len(name)-3:len(name)]        ##更加后缀名拦截一些不需要的文件        ##拦截规则可以自定定义        if  filetype =='pbl':                print ("pbl 文件被拦截 -->"+name)        elif  filetype =='pbr':                print ("pbr 文件被拦截 -->"+name)        elif  filetype == 'pbw':                print ("pbw 文件被拦截 -->"+name)        elif  filetype == 'pbt':                print ("pbt 文件被拦截 -->"+name)        else:                print(name[len(name)-3:len(name)])                out.write(name+'\n')out.close()

run.py源码如下:

#encoding: utf-8import osimport sysimport shutilimport timeif __name__ == "__main__":        curdir = os.getcwd()        namefile = "names.txt"        if os.path.isfile(namefile):                print("文件列表以检测到,正在读取....")        else:                print("未找到names.txt文件,程序结束")                ##sys.exit()                        tag = ''        while ( not os.path.isdir(tag)):                tag = raw_input('输入目标路径:')                if not os.path.isdir(tag):                        os.mkdir(tag)                                tag = tag+'\\'             nfile = open(namefile)        for line in nfile:                        src = line[:-1]                                shutil.copy(src,tag)                print(src+' 复制到 '+tag)        nfile.close

编橙之家文章,

评论关闭