Below for you to share a Python read file name generation list method, has a good reference value, I hope to be helpful to everyone. Come and see it together.
It is often necessary to read all the image files under a folder.
I used python to write a simple code that reads a file with a suffix in a folder and makes the file name into text (CSV format)
Import Fnmatchimport Osimport pandas as Pdimport NumPy as NP import Sysinputstra = SYS.ARGV[1]INPUTSTRB = Sys.argv[2]def R EADSAVEADDR (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)
The above code is saved as: getlst.py
When used:
In the cmd window, enter:
Python getlst.py f:/train/pos *.png
found that the above code can not go deep into the next level of directory, but also made a few changes:
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 the 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# output absolute path 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!")