python method to read file names and generate list

不言
Release: 2018-04-27 11:20:31
Original
4730 people have browsed it

下面为大家分享一篇python读取文件名称生成list的方法,具有很好的参考价值,希望对大家有所帮助。一起过来看看吧

经常需要读取某个文件夹下所有的图像文件。

我使用python写了个简单的代码,读取某个文件夹下某个后缀的文件,将文件名生成为文本(csv格式)

import fnmatch
import os
import pandas as pd
import numpy as np 
import sys
InputStra = sys.argv[1]
InputStrb = sys.argv[2]
def ReadSaveAddr(Stra,Strb):
 #print(Stra)
 #print(Strb)
 print("Read :",Stra,Strb)
 a_list = fnmatch.filter(os.listdir(Stra),Strb)
 print("Find = ",len(a_list))
 df = pd.DataFrame(np.arange(len(a_list)).reshape((len(a_list),1)),columns=['Addr']) 
 df.Addr = a_list
 #print(df.head())
 df.to_csv('Get.lst',columns=['Addr'],index=False,header=False)
 print("Write To Get.lst !")
ReadSaveAddr(InputStra,InputStrb)
Copy after login

上面代码保存为:GetLst.py

使用时:

在cmd窗口输入:

python GetLst.py F:/train/pos *.png
Copy after login

发现上面代码不能深入到下一层目录,又做了点修改:

def ReadSaveAddr2(Stra,Strb):
 df = pd.DataFrame(np.arange(0).reshape(0,1),columns=['Addr']) 
 print(df)
 path = InputStra
 for dirpath,dirnames,filenames in os.walk(path):
  #for filename in filenames:
  a_list = fnmatch.filter(os.listdir(dirpath),Strb)
  if len(a_list):
   dft = pd.DataFrame(np.arange(len(a_list)).reshape((len(a_list),1)),columns=['Addr']) 
   dft.Addr = a_list
   dft.Addr = dirpath + '\\' + dft.Addr#输出绝对路径
   frames = [df,dft]
   df = pd.concat(frames)
   print(df.shape)
 df.to_csv('Get.lst',columns='Addr'],index=False,header=False)
 print("Write To Get.lst !")
Copy after login

相关推荐:

Python 读取指定文件夹下的所有图像方法

The above is the detailed content of python method to read file names and generate list. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template