027 获取指定路径所有文件的路径名

 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
# -*- coding: utf-8 -*-
"""
Created on Sun Apr 28 18:20:50 2019

@author: zangz
"""
import os
import os.path

#函数查找指定路径中所有文件的路径
def get_file(path):
    list1=[]#用于存储递归查找到的所有文件,传递给函数
    fileList = os.listdir(path)  # 获取path目录下所有文件
    for filename in fileList:
        pathTmp = os.path.join(path,filename) # 获取path与filename组合后的路径
        if os.path.isdir(pathTmp):  # 如果是目录
            a=get_file(pathTmp) # 则递归查找(注意一定要有接受变量,不然就出错了)
            for i in a:
                list1.append(i)
        else: 
            list1.append(pathTmp)
    return list1

path = input('请输入路径:').strip()  #.strip()去除首尾的空格

file_path_list=get_file(path)


#循环打印所有文件路径
for filepath in file_path_list:
    print(filepath+'\n')

执行结果:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
runfile('K:/python程序/获取指定路径所有文件及其路径.py', wdir='K:/python程序')

请输入路径K:\python程序
K:\python程序\123.txt

K:\python程序\copy筛选的文件.py

K:\python程序\file_path\123.txt

K:\python程序\file_path\合并std的文字.py

K:\python程序\file_path\哈哈1.txt

K:\python程序\file_path\新建文件夹\新建文本文档.txt

K:\python程序\glob模块的使用.py

K:\python程序\MP3到wav格式的转换.py

K:\python程序\numpy的操作\numpy_operation.py

K:\python程序\python题目.py
.....