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')
python 文件操作之open,read,write
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 = r'E:\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))