python自動找出當(dāng)前文件夾下的指定文件類型,并將路徑導(dǎo)出到j(luò)s文件

適用于cocos creator項目需要動態(tài)加載文件時,導(dǎo)出的js文件直接require就能使用,格式為數(shù)組

# -*- coding: utf-8 -*-  
import os 
import io 
import json
  
def listdir(path, list_name):  
    for file in os.listdir(path):  
        file_path = os.path.join(path, file)  
        if os.path.isdir(file_path):  
            listdir(file_path, list_name)  
        elif os.path.splitext(file_path)[1]=='.png':
            text = '\\resources\\'
            text1 = '.png'
            length = len(file_path)
            idx = file_path.find(text)
            if idx != -1 :
                idx = idx + len(text)
                file_path = file_path[idx:(length)]
            idx = file_path.find(text1)
            if idx != -1 :
                file_path = file_path[0:idx]
            file_path = file_path.replace('\\', '/')
            list_name.append(file_path)
            print(text,"+++++",file_path)
# -*- coding: utf-8 -*-   
  
# import os  
  
# def file_name(file_dir):   
    # for root, dirs, files in os.walk(file_dir):  
        # print(root) #當(dāng)前目錄路徑  
        # print(dirs) #當(dāng)前路徑下所有子目錄  
        # print(files) #當(dāng)前路徑下所有非目錄子文件 
if __name__ == '__main__':
    curPath = os.path.dirname(os.path.abspath(__file__))
    name_list = []
    listdir(curPath,name_list)
    # file_name(curPath)
    # wreteList = 'module.exports = ['+','.join(name_list)+']'
    text = '\\assets\\'
    goalPath = 'scripts\\common\\'
    length = len(curPath)
    idx = curPath.find(text)
    if idx != -1 :
        idx = idx + len(text)
        curPath = curPath[0:idx]+goalPath
    jsonPath = os.path.join(curPath,"ImagePath.js") #寫入路徑
    print(jsonPath)
    dirname = os.path.dirname(jsonPath)
    if not os.path.exists(dirname):
        os.makedirs(dirname)
    with io.open(jsonPath, 'w', encoding='utf-8') as f:     #按照對應(yīng)路徑寫入
        f.write('module.exports = ')
        f.write(json.dumps(name_list, ensure_ascii=False, indent=4, sort_keys=True))
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容