Python批量读取文件名并写入TXT文件的实现方法

纸上星河
纸上星河
发布时间:2026-10-13 | 3人浏览过
原创

本文介绍利用Python脚本批量读取指定目录下的文件名,并将其写入TXT文件的方法。通过递归遍历目录结构,过滤特定后缀如.meta,并将文件名提取后保存至指定路径的文本文件中,适用于Unity等需要动态加载资源的项目场景,提供完整代码参考。

Python批量读取文件名并写入TXT文件的实现方法

本文分享一段Python代码,用于批量读取文件名并将结果写入TXT文件,供开发者参考。

在项目实施过程中,常需动态加载图片资源。若使用Unity的Resources.Load方法,面对上百张图片,逐一手动编写加载路径极为繁琐。虽然最初尝试逐个编辑并存入数组,但效率低下,因此需要一个自动化工具来批量生成这些路径信息。

基于上述需求,以下提供具体实现代码。代码注释较少,如有疑问欢迎留言,我会及时回复解答。

核心代码实现与逻辑解析


#coding=utf-8
import sys
import os, glob
 
reload(sys)
sys.setdefaultencoding('utf-8')
 
#输出路径,自行修改
TxtPath="C://Users//yupu//Desktop//f.txt"
 
def BFS_Dir(dirPath, dirCallback = None, fileCallback = None):
 queue = []
 ret = []
 f=open(TxtPath,'w') # r只读,w可写,a追加
 queue.append(dirPath);
 while len(queue) > 0:
  tmp = queue.pop(0)
  if(os.path.isdir(tmp)):
   ret.append(tmp)
   for item in os.listdir(tmp):
    queue.append(os.path.join(tmp, item))
   if dirCallback:
    dirCallback(tmp)
  elif(os.path.isfile(tmp)):
   ret.append(tmp)
   if fileCallback:
    mPath , ext = os.path.splitext(tmp)
    names = os.path.split(mPath)
    if(ext==".meta"):
     continue
    else:
    print names[1]
    f.write(names[1])
    f.write('\n')
    fileCallback(tmp)
 f.close()
 return ret
 
def printDir(dirPath):
 print "dir: " + dirPath
 
def printFile(dirPath):
 print "file: " + dirPath
 
if __name__ == '__main__':
 while True:
  path = raw_input("Path:")
  try:
   b = BFS_Dir(path , printDir, printFile)
   print ("\r\n   *******\r\n"+"*********Done*********"+"\r\n   **********\r\n")
  except:
   print "Unexpected error:", sys.exc_info()
  raw_input('press enter key to rehandle')

以上即为本文的全部内容,希望能为您的学习提供便利,也欢迎继续支持本站。

本站声明

本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。

Python 相关产品和应用

全部下载

专题列表