首页 > 编程语言 > 详细

用python遍历一个图片文件夹,并输出所有路径到一个 txt 文件

时间:2020-02-29 15:20:08      阅读:192      评论:0      收藏:0      [点我收藏+]
 1 #coding:utf8
 2 import os
 3 import sys
 4 def listfiles(rootDir, txtfile, label=0):
 5     ftxtfile = open(txtfile, w)
 6     list_dirs = os.walk(rootDir)
 7     count = 0
 8     dircount = 0
 9     for root,dirs,files in list_dirs:
10         for d in dirs:
11             print(os.path.join(root, d))
12             dircount += 1
13         for f in files:
14              print(os.path.join(root, f))
15              ftxtfile.write(os.path.join(root, f)+   + str(label) + \n)
16              count += 1
17     print(rootDir +  has  + str(count) +  files)
18 
19 listfiles(E:/data/pic, E:/data/txtfile.txt)

1、open

#open(filepath , ‘mode‘)

file = open(‘E:/data/testfile.txt’,‘w’)  

一般常用模式:r(只读)、w(只写)、a(追加)、b(二进制)

组合:r+(读写)、w+(读写) 

2、读文件(r): read()         readline()           readlines()

file = open(‘D/test/test.txt‘,‘r‘)   #只读模式打开file

3、write(w)

1 file = open(E:/data/txtfile.txt,w+)   #只写模式打开file
2 file.write(11111)

技术分享图片

python的os.walk()函数的使用及对于root,dirs,files的理解

root指的是当前所在的文件夹路径,dirs是当前文件夹路径下的文件夹列表,files是当前文件夹路径下的文件列表。

所以我们可以通过root和dirs的某项组合出文件夹路径,通过root和files的某项组合出文件路径。

1 import os
2 path = rE:\data\pic
3 for root, dirs, files in os.walk(path):
4     #print(root, dirs, files)
5     for name in files:
6         print(os.path.join(root,name))
7     for name in dirs:
8         print(os.path.join(root,name))

 

 技术分享图片

 

用python遍历一个图片文件夹,并输出所有路径到一个 txt 文件

原文:https://www.cnblogs.com/Lazycat1206/p/12382864.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!