search
HomeBackend DevelopmentPython Tutorialpython method to read file names and generate list

python method to read file names and generate list

Apr 27, 2018 am 11:20 AM
pythonnamegenerate

下面为大家分享一篇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 !")

相关推荐:

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!

Statement
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
What data types can be stored in a Python array?What data types can be stored in a Python array?Apr 27, 2025 am 12:11 AM

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

What happens if you try to store a value of the wrong data type in a Python array?What happens if you try to store a value of the wrong data type in a Python array?Apr 27, 2025 am 12:10 AM

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

Which is part of the Python standard library: lists or arrays?Which is part of the Python standard library: lists or arrays?Apr 27, 2025 am 12:03 AM

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

What should you check if the script executes with the wrong Python version?What should you check if the script executes with the wrong Python version?Apr 27, 2025 am 12:01 AM

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

What are some common operations that can be performed on Python arrays?What are some common operations that can be performed on Python arrays?Apr 26, 2025 am 12:22 AM

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

In what types of applications are NumPy arrays commonly used?In what types of applications are NumPy arrays commonly used?Apr 26, 2025 am 12:13 AM

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

When would you choose to use an array over a list in Python?When would you choose to use an array over a list in Python?Apr 26, 2025 am 12:12 AM

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

Are all list operations supported by arrays, and vice versa? Why or why not?Are all list operations supported by arrays, and vice versa? Why or why not?Apr 26, 2025 am 12:05 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools