python读取文件名称生成list的方法
作者:masbbx123 时间:2021-12-21 02:40:34
经常需要读取某个文件夹下所有的图像文件。
我使用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 !")
来源:https://blog.csdn.net/masbbx123/article/details/78954294
标签:python,读取,文件,list
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
用Python进行TCP网络编程的教程
2021-07-31 06:06:07
![](https://img.aspxhome.com/file/2023/3/89453_0s.png)
Flask模板引擎之Jinja2语法介绍
2021-11-15 21:08:11
Python将Excel表格按某列拆分为多个sheet实现过程
2021-06-11 06:59:54
jquery密码强度测试工具源码
2009-12-23 19:38:00
![](https://img.aspxhome.com/file/UploadPic/20101/11/2009106204119-12s.png)
Asp 日期格式化问题
2011-03-31 10:47:00
laravel 实现阿里云oss文件上传功能的示例
2023-06-13 20:39:26
![](https://img.aspxhome.com/file/2023/2/55532_0s.jpg)
浅谈Python的条件判断语句if/else语句
2021-03-06 12:11:02
php生成随机数/生成随机字符串的方法小结【5种方法】
2023-09-05 20:23:21
Chrome调试折腾记之JS断点调试技巧
2023-07-07 16:35:08
![](https://img.aspxhome.com/file/2023/1/55901_0s.png)
macOS Sierra安装Apache2.4+PHP7.0+MySQL5.7.16
2023-11-15 13:05:39
![](https://img.aspxhome.com/file/2023/5/78105_0s.jpg)
利用python汇总统计多张Excel
2023-12-31 14:22:11
![](https://img.aspxhome.com/file/2023/0/77690_0s.jpg)
python中的插入排序的简单用法
2023-09-30 07:57:51
![](https://img.aspxhome.com/file/2023/3/63193_0s.png)
Dreamweaver MX 2004 制作树状菜单教程[动画]
2010-03-25 12:24:00
MS Server和Oracle中对NULL处理的一些细节差异
2009-06-10 17:35:00
HTML5本地存储初探(一)
2010-03-07 15:42:00
![](https://img.aspxhome.com/file/UploadPic/20103/7/20100127-nt3aii2bftxqusxnd37rixkyjy-30s.png)
python实现套接字创建
2021-09-09 05:12:04
用python写测试数据文件过程解析
2022-03-24 16:54:57
![](https://img.aspxhome.com/file/2023/8/69588_0s.png)
Python3 ID3决策树判断申请贷款是否成功的实现代码
2021-02-11 15:01:58
![](https://img.aspxhome.com/file/2023/4/82914_0s.png)
JavaScript实现点击按钮复制指定区域文本(推荐)
2023-08-22 17:36:30
python实现彩票系统
2021-04-12 21:16:42