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

转自https://blog.csdn.net/xxn_723911/article/details/78795033

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
可以使用如下代码获取每个文件的绝对路径:
>>> 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()可获得:
>>> 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']
parent:列出了目录路径下面所有存在的目录的名称
dirnames:文件夹名
filenames:列出了目录路径下面所有文件的名称
通过下面代码可获得给定路径下所有的文件路径:
>>> 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.按格式输出。
代码演示:
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)
运行结果如下:

猜你喜欢

转载自blog.csdn.net/originalcandy/article/details/85046682