Python 读取指定文件夹里的所有文件名

项目需要:把资源文件夹里的图片全部找出来,按格式写出所有图片的路径。

最近学了下Python,把这个脚本写出来运行下。

运行结果:

注释:

PATH_RESOURCE  指放资源的文件夹,里面的图片可以随意放置在各种子文件夹下。

代码:

#!/usr/bin/python3

'''
Function This document is used to read resource from files and then write them.
Date     2018-07-04
Author   Randy Lee
'''

import os

PATH_RESOURCE = 'Resource/'                 #Read resource from this path
PATH_HEAD     = 'file://./'                 #Head of the resourec route
PATH_CREAT    = 'HMI/Warning/Resource.hpp'  #Write data to this document

Data_List = [] #Storage data to Data_List list

nl = '\n'
LEFT_WIDTH = 70

#####################################################################
# Function load resource to Data_List
#####################################################################
def loadResource():
    for root, dirs, files in os.walk(PATH_RESOURCE):
        for m_file in files:
            Data_List.append(PATH_HEAD + root + '/' + m_file);
            #print(PATH_HEAD + root + '/' + m_file);

#####################################################################
# Function write data from Data_List to Resource.hpp
#####################################################################
def creatResource():
    resource_hpp = open(PATH_CREAT, 'w')
    
    ctt = ''
    ctt += nl
    
    for txt in Data_List:
        info_head = (txt.split('.')[1]).upper().replace('/','_')
        info_tail = (txt.split('.')[2]).upper()
        # Define left
        info_define = "#define RES_PATH" + info_head + '_' + info_tail
        # Keep alignment on the left
        space = alignment(LEFT_WIDTH, info_define)
        # All route every line
        ctt += info_define + space + '"' + txt + '"' + nl

    resource_hpp.write(ctt)
    resource_hpp.close

#####################################################################
# Function for alignment
#####################################################################
def alignment(width, str):
    m_space = ''
    
    if (width > len(str)):
        m_space = ' ' * (width - len(str))
    return m_space

#####################################################################
# Generate all functions
#####################################################################
def Gen():
    loadResource()
    creatResource()

#####################################################################
#
#####################################################################
if __name__ == '__main__':
    Gen()

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值