项目需要:把资源文件夹里的图片全部找出来,按格式写出所有图片的路径。
最近学了下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()