我是靠谱客的博主 高大哈密瓜,这篇文章主要介绍python2.7里边目录python列出文件夹里面的所有内容,现在分享给大家,希望可以做个参考。

  • 前段时间为了做笔记,需要找到目录里面的所有文件和文件夹啊的内容,并且列出他们的名字,作为记录,网上一搜没找到,不合心意,于是用python写了一个,可以列出目录里面的所有文件和文件夹的名字,用法:修改path_to_list指定你要遍历的目录,dirNamesTextFile指定你要把遍历结果文字存起来的文件

    复制代码
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    # -*- 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)

最后

以上就是高大哈密瓜最近收集整理的关于python2.7里边目录python列出文件夹里面的所有内容的全部内容,更多相关python2.7里边目录python列出文件夹里面内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(55)

评论列表共有 0 条评论

立即
投稿
返回
顶部