python2.7里边目录python列出文件夹里面的所有内容

来源:互联网 发布:python的sorted函数 编辑:程序博客网 时间:2024/06/11 20:33
  • 前段时间为了做笔记,需要找到目录里面的所有文件和文件夹啊的内容,并且列出他们的名字,作为记录,网上一搜没找到,不合心意,于是用python写了一个,可以列出目录里面的所有文件和文件夹的名字,用法:修改path_to_list指定你要遍历的目录,dirNamesTextFile指定你要把遍历结果文字存起来的文件

        # -*- coding: UTF-8 -*-    import os    ## 一定要注意,添加utf8的支持,否则无法打印文件名字,python打印中午,python识别中文,    ## python打印文件夹内容,python列出文件夹里面的内容,python获得当前目录的所有文件名,python list dir    path_to_list='F:\\VMshare\\NI_multisim_sim_projects'    dirNamesTextFile='E:\\testing_projects\\python_get_dir_files_names.txt'    #### python列出目录下所有在名字,python列出目录中文名,python获取文件夹里面的所有文件名字获取文件夹里面就所有文件名字;    def python_list_dir_names(urPath):        dirNames=os.listdir(urPath)        for ones in dirNames:            print ones.decode('gbk')###转换编码格式,python编码格式转换,python转换编码格式        return dirNames    def getfilelist(filepath, tabnum=1):   #####带子目录的历遍,带子目录的历遍        simplepath = os.path.split(filepath)[1]        returnstr = simplepath+' Dir: '+'\n'        returndirstr = ""        returnfilestr = ""        filelist = os.listdir(filepath)        for num in range(len(filelist)):            filename=filelist[num]            if os.path.isdir(filepath+"\\"+filename):###win32 ,windows                returndirstr += "\t"*tabnum+getfilelist(filepath+"\\"+filename, tabnum+1)            else:                returnfilestr += "\t"*tabnum+filename+"\n"        returnstr += returnfilestr+returndirstr        return returnstr+"\t"*tabnum+"</>\n"    def python_save_chinese_gb2312_strings_in_one_file(urStingsToWrite, urFileWithPath):    #    if 'str'!=type(urStingsToWrite):  ####原来我写的,不能历遍子目录的,    #        for i in urStingsToWrite:  ####原来我写的,不能历遍子目录的,    #            print i.decode('gbk')##python转换编码,python编码转换,python读写文件,python gbk python gb2312  ####原来我写的,不能历遍子目录的,        print urStingsToWrite        try:            outPutFileHandle = open(urFileWithPath, 'w')##python打开文件,python读文件,        except:            print ("Error opening files:", urFileWithPath)            outPutFileHandle.close()            return        try:            for str in urStingsToWrite:    #            if with_newline_or_not:####原来我写的,不能历遍子目录的,    #                str = str + '\n'####原来我写的,不能历遍子目录的,                outPutFileHandle.write(str)            outPutFileHandle.close()        except:            outPutFileHandle.close()            print ("Error writing files:", urFileWithPath)        return    ####names_string_buffer=python_list_dir_names(path_to_list)  ####原来我写的,不能历遍子目录的,    names_string_buffer=getfilelist(path_to_list)    python_save_chinese_gb2312_strings_in_one_file(names_string_buffer,dirNamesTextFile)
0 0
原创粉丝点击