获取文件路径----os.listdir()和os.walk()

      版权声明:本文为博主原创文章,未经博主允许不得转载。          https://blog.csdn.net/xxn_723911/article/details/78795033        </div>
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
                          <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
      <div class="htmledit_views" id="content_views">

1.os.listdir(path='')

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

2.walk(top, topdown=True, οnerrοr=None, followlinks=False)

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

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

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

   
   
  1. test_file:
  2. test1.txt
  3. test2.txt
  4. test3.txt
可以使用如下代码获取每个文件的绝对路径:

   
   
  1. >>> import os
  2. >>> path = r'C:\Users\XXN\Desktop\test_file'
  3. >>> for each_file in os.listdir(path):
  4. print(os.path.join(path,each_file))
  5. 结果如下:
  6. C:\Users\XXN\Desktop\test_file\test1.txt
  7. C:\Users\XXN\Desktop\test_file\test2.txt
  8. C:\Users\XXN\Desktop\test_file\test3.txt

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

    
    
  1. Test_file:
  2. file1:
  3. test1.txt
  4. test2.txt
  5. test3.txt
  6. file2:
  7. test1.txt
  8. test2.txt
  9. test3.txt
  10. test1.txt
  11. test2.txt
  12. test3.txt
使用os.walk()可获得:

    
    
  1. >>> import os
  2. >>> path = r'C:\Users\XXN\Desktop\test_file'
  3. >>> for parent,dirnames,filenames in os.walk(path):
  4. print(parent,dirnames,filenames)
  5. 结果如下:
  6. C:\Users\XXN\Desktop\test_file [ 'file1', 'file2'] [ 'test1.txt', 'test2.txt', 'test3.txt']
  7. C:\Users\XXN\Desktop\test_file\file1 [] [ 'test1.txt', 'test2.txt', 'test3.txt']
  8. C:\Users\XXN\Desktop\test_file\file2 [] [ 'test1.txt', 'test2.txt', 'test3.txt']
parent:列出了目录路径下面所有存在的目录的名称
dirnames:文件夹名
filenames:列出了目录路径下面所有文件的名称
通过下面代码可获得给定路径下所有的文件路径:

    
    
  1. >>> import os
  2. >>> path = r'C:\Users\XXN\Desktop\test_file'
  3. >>> for parent,dirnames,filenames in os.walk(path):
  4. for filename in filenames:
  5. print(os.path.join(parent,filename))
  6. 结果如下:
  7. C:\Users\XXN\Desktop\test_file\test1.txt
  8. C:\Users\XXN\Desktop\test_file\test2.txt
  9. C:\Users\XXN\Desktop\test_file\test3.txt
  10. C:\Users\XXN\Desktop\test_file\file1\test1.txt
  11. C:\Users\XXN\Desktop\test_file\file1\test2.txt
  12. C:\Users\XXN\Desktop\test_file\file1\test3.txt
  13. C:\Users\XXN\Desktop\test_file\file2\test1.txt
  14. C:\Users\XXN\Desktop\test_file\file2\test2.txt
  15. C:\Users\XXN\Desktop\test_file\file2\test3.txt

应用3:编写一个程序,用户输入关键字,查找当前文件夹内(如果当前文件夹内包含文件夹,则进入文件夹继续搜索)所有含有该关键字的文本文件(.txt后缀),要求显示该文件所在的位置以及关键字在文件中的具体位置(第几行第几个字符)
思路:1.先把当前文件夹下的.txt文件以及当前文件包含的子文件夹中的.txt文件的路径全部保存至一个txt_list列表中;2.以读取的方式打开txt_list中每个路径的文件,并将每个文件中出现关键字的行数以及关键字索引保存至一个字典dict_keywords中。3.按格式输出。
代码演示:

    
    
  1. import os
  2. def print_keywords(dict_keywords):
  3. keys = dict_keywords.keys()
  4. keys = sorted(keys)
  5. for each in keys:
  6. print( '关键字出现在第 %s 行,第 %s 个位置。'% (each, str(dict_keywords[each])))
  7. def line_keywords(line, keywords):
  8. key_index = []
  9. start = line.find(keywords)
  10. while start!= -1:
  11. key_index.append(start+ 1)
  12. start = line.find(keywords, start+ 1)
  13. return key_index
  14. def file_keywords(filename, keywords):
  15. f = open(filename, 'r')
  16. line = 0
  17. dict_keywords = dict()
  18. for each_line in f:
  19. line += 1
  20. if keywords in each_line:
  21. key_index = line_keywords(each_line, keywords)
  22. dict_keywords[line]= key_index
  23. f.close()
  24. return dict_keywords
  25. def file_search(keywords, flag):
  26. all_files = os.walk(os.getcwd())
  27. txt_list = []
  28. for each in all_files:
  29. for filename in each[ 2]:
  30. if os.path.splitext(filename)[ 1] == '.txt':
  31. txt_list.append(os.path.join(each[ 0],filename))
  32. for each_txt_file in txt_list:
  33. dict_keywors = file_keywords(each_txt_file, keywords)
  34. print( '====================================================')
  35. print( '在文件【%s】中找到关键字【%s】' % (each_txt_file, keywords))
  36. if flag in [ 'YES', 'Yes', 'yes']:
  37. print_keywords(dict_keywors)
  38. keywords = input( "请将该脚本放于待查找的文件夹中,请输入关键字:")
  39. flag = input( "请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):")
  40. file_search(keywords, flag)
运行结果如下:


      版权声明:本文为博主原创文章,未经博主允许不得转载。          https://blog.csdn.net/xxn_723911/article/details/78795033        </div>
        <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
                          <link rel="stylesheet" href="https://csdnimg.cn/release/phoenix/template/css/ck_htmledit_views-f57960eb32.css">
      <div class="htmledit_views" id="content_views">

猜你喜欢

转载自blog.csdn.net/j879159541/article/details/90489772
今日推荐