下面为大家分享一篇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)
上面代码保存为:GetLst.py
使用时:
在cmd窗口输入:
python GetLst.py F:/train/pos *.png
发现上面代码不能深入到下一层目录,又做了点修改:
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 !")
相关推荐:
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!

Pythonlistscanstoreanydatatype,arraymodulearraysstoreonetype,andNumPyarraysarefornumericalcomputations.1)Listsareversatilebutlessmemory-efficient.2)Arraymodulearraysarememory-efficientforhomogeneousdata.3)NumPyarraysareoptimizedforperformanceinscient

WhenyouattempttostoreavalueofthewrongdatatypeinaPythonarray,you'llencounteraTypeError.Thisisduetothearraymodule'sstricttypeenforcement,whichrequiresallelementstobeofthesametypeasspecifiedbythetypecode.Forperformancereasons,arraysaremoreefficientthanl

Pythonlistsarepartofthestandardlibrary,whilearraysarenot.Listsarebuilt-in,versatile,andusedforstoringcollections,whereasarraysareprovidedbythearraymoduleandlesscommonlyusedduetolimitedfunctionality.

ThescriptisrunningwiththewrongPythonversionduetoincorrectdefaultinterpretersettings.Tofixthis:1)CheckthedefaultPythonversionusingpython--versionorpython3--version.2)Usevirtualenvironmentsbycreatingonewithpython3.9-mvenvmyenv,activatingit,andverifying

Pythonarrayssupportvariousoperations:1)Slicingextractssubsets,2)Appending/Extendingaddselements,3)Insertingplaceselementsatspecificpositions,4)Removingdeleteselements,5)Sorting/Reversingchangesorder,and6)Listcomprehensionscreatenewlistsbasedonexistin

NumPyarraysareessentialforapplicationsrequiringefficientnumericalcomputationsanddatamanipulation.Theyarecrucialindatascience,machinelearning,physics,engineering,andfinanceduetotheirabilitytohandlelarge-scaledataefficiently.Forexample,infinancialanaly

Useanarray.arrayoveralistinPythonwhendealingwithhomogeneousdata,performance-criticalcode,orinterfacingwithCcode.1)HomogeneousData:Arrayssavememorywithtypedelements.2)Performance-CriticalCode:Arraysofferbetterperformancefornumericaloperations.3)Interf

No,notalllistoperationsaresupportedbyarrays,andviceversa.1)Arraysdonotsupportdynamicoperationslikeappendorinsertwithoutresizing,whichimpactsperformance.2)Listsdonotguaranteeconstanttimecomplexityfordirectaccesslikearraysdo.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version
Visual web development tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

WebStorm Mac version
Useful JavaScript development tools
