当前位置:脚本大全 > > 正文

python 自定义获取文件目录(Python使用os.listdir和os.walk获取文件路径与文件下所有目录的方法)

时间:2021-10-23 10:43:25类别:脚本大全

python 自定义获取文件目录

Python使用os.listdir和os.walk获取文件路径与文件下所有目录的方法

在python3.6版本中去掉了os.path.walk()函数

os.walk()

函数声明:walk(top,topdown=True,oneerror=None)

os.walk()实例:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • import os
  • def walk(path):
  •   if not os.path.exists(path):
  •     return -1
  •   for root,dirs,names in os.walk(path):
  •     for filename in names:
  •       print(os.path.join(root,filename)) #路径和文件名连接构成完整路径
  • if __name__=='__main__':
  •   path = "C:\\Users\\Administrator\\Desktop\\2017-9-1"
  •   walk(path)
  • 输出结果:

    C:\Users\Administrator\Desktop\2017-9-1\2017-9-1.txt
    C:\Users\Administrator\Desktop\2017-9-1\2017-9-1storage.txt
    C:\Users\Administrator\Desktop\2017-9-1\apk.conf
    C:\Users\Administrator\Desktop\2017-9-1\数据采集导入质量统计_2017-09-01.docx
    C:\Users\Administrator\Desktop\2017-9-1\test1\2017-9-1.txt
    C:\Users\Administrator\Desktop\2017-9-1\test2\2017-9-1.txt

    1.os.listdir(path='')

    其中参数path为需要列出的目录路径。该函数返回指定的文件夹包含的文件或文件夹的名字的列表。

    2.walk(top, topdown=True, onerror=None, followlinks=False)

    os.walk(path)返回三个值:parent, dirnames, filenames,分别表示path的路径、path路径下的文件夹的名字和path路径下文件夹以外的其他文件。

    应用1:在一个目录下面只有文件时可以使用os.listdir()。

    比如文件test_file文件中包含三个文件,即:

    test_file:
             test1.txt
             test2.txt
             test3.txt

    可以使用如下代码获取每个文件的绝对路径:

  • ?
  • 1
  • 2
  • 3
  • 4
  • >>> import os
  • >>> path = r'C:\Users\XXN\Desktop\test_file'
  • >>> for each_file in os.listdir(path):
  •  print(os.path.join(path,each_file))
  • 结果如下:

    C:\Users\XXN\Desktop\test_file\test1.txt
    C:\Users\XXN\Desktop\test_file\test2.txt
    C:\Users\XXN\Desktop\test_file\test3.txt

    应用2:当一个目录下面既有文件又有目录(文件夹),可使用os.walk()读取里面所有文件。

    比如文件test_file中既包含文件也包含文件夹:

    Test_file:
            file1:
                 test1.txt
                 test2.txt
                 test3.txt
            file2:
                 test1.txt
                 test2.txt
                 test3.txt
            test1.txt
            test2.txt
            test3.txt

    使用os.walk()可获得:

  • ?
  • 1
  • 2
  • 3
  • 4
  • >>> import os
  • >>> path = r'C:\Users\XXN\Desktop\test_file'
  • >>> for parent,dirnames,filenames in os.walk(path):
  •  print(parent,dirnames,filenames)
  • 结果如下:

    C:\Users\XXN\Desktop\test_file ['file1', 'file2'] ['test1.txt', 'test2.txt', 'test3.txt']
    C:\Users\XXN\Desktop\test_file\file1 [] ['test1.txt', 'test2.txt', 'test3.txt']
    C:\Users\XXN\Desktop\test_file\file2 [] ['test1.txt', 'test2.txt', 'test3.txt']

    通过下面代码可获得给定路径下所有的文件路径:

  • ?
  • 1
  • 2
  • 3
  • 4
  • 5
  • >>> import os
  • >>> path = r'C:\Users\XXN\Desktop\test_file'
  • >>> for parent,dirnames,filenames in os.walk(path):
  •  for filename in filenames:
  •  print(os.path.join(parent,filename))
  • 结果如下:

    C:\Users\XXN\Desktop\test_file\test1.txt
    C:\Users\XXN\Desktop\test_file\test2.txt
    C:\Users\XXN\Desktop\test_file\test3.txt
    C:\Users\XXN\Desktop\test_file\file1\test1.txt
    C:\Users\XXN\Desktop\test_file\file1\test2.txt
    C:\Users\XXN\Desktop\test_file\file1\test3.txt
    C:\Users\XXN\Desktop\test_file\file2\test1.txt
    C:\Users\XXN\Desktop\test_file\file2\test2.txt
    C:\Users\XXN\Desktop\test_file\file2\test3.txt

    应用3:编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符)

    思路:

    1.先把当前文件夹下的.txt文件以及当前文件包含的子文件夹中的.txt文件的路径全部保存至一个txt_list列表中;

    2.以读取的方式打开txt_list中每个路径的文件,并将每个文件中出现关键字的行数以及关键字索引保存至一个字典dict_keywords中。

    3.按格式输出。

    代码演示:

  • ?
  • 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
  • import os
  • def print_keywords(dict_keywords):
  •   keys = dict_keywords.keys()
  •   keys = sorted(keys)
  •   for each in keys:
  •     print('关键字出现在第 %s 行,第 %s 个位置。'% (each, str(dict_keywords[each])))
  • def line_keywords(line, keywords):
  •   key_index = []
  •   start = line.find(keywords)
  •   while start!=-1:
  •     key_index.append(start+1)
  •     start = line.find(keywords, start+1)
  •   return key_index   
  • def file_keywords(filename, keywords):
  •   f = open(filename,'r')
  •   line = 0
  •   dict_keywords = dict()
  •   for each_line in f:
  •     line +=1
  •     if keywords in each_line:
  •         key_index = line_keywords(each_line, keywords)
  •         dict_keywords[line]= key_index
  •   f.close()
  •   return dict_keywords
  • def file_search(keywords, flag):
  •   all_files = os.walk(os.getcwd())
  •   txt_list = []
  •   for each in all_files:
  •     for filename in each[2]:
  •       if os.path.splitext(filename)[1] == '.txt':
  •         txt_list.append(os.path.join(each[0],filename))
  •   for each_txt_file in txt_list:
  •     dict_keywors = file_keywords(each_txt_file, keywords)
  •     print('====================================================')
  •     print('在文件【%s】中找到关键字【%s】' % (each_txt_file, keywords))
  •     if flag in ['YES', 'Yes', 'yes']:
  •        print_keywords(dict_keywors)
  • keywords = input("请将该脚本放于待查找的文件夹中,请输入关键字:")
  • flag = input("请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):")
  • file_search(keywords, flag)
  • 运行结果如下:

    python 自定义获取文件目录(Python使用os.listdir和os.walk获取文件路径与文件下所有目录的方法)

    总结

    以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对开心学习网的支持。如果你想了解更多相关内容请查看下面相关链接

    原文链接:https://blog.csdn.net/sxf_123456/article/details/77857057

    上一篇下一篇

    猜您喜欢

    热门推荐