Python read file name method for generating list

Source: Internet
Author: User
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!")

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.