# coding=gbk
import os
import os.path
#讀取目錄下的全部文件,包括嵌套的文件夾
def GetFileList(dir, fileList):
newDir = dir
if os.path.isfile(dir):
fileList.append(dir)
elif os.path.isdir(dir):
for s in os.listdir(dir):
# 若是須要忽略某些文件夾,使用如下代碼
# if s == "xxx":
# continue
newDir = os.path.join(dir, s)
GetFileList(newDir, fileList)
return fileList
fileDir = "E:\\Differnernt_Size_Digit_Data\\ReSize\\Train\\28x28"
list = GetFileList(fileDir, [])
# 打開一個文件
fo = open("file_list.txt", "w") # 打開文件
for i in list:
print(i) # 測試完整文件路徑
print(os.path.basename(i)) # 文件名
index = i.find(".", 0) # 找到點號的位置
print(i[index - 1:index]) # 截取目標字符
print(os.path.basename(i) + " " + i[index - 1:index]) # 測試目標字符串
fo.write(os.path.basename(i) + " " + i[index - 1:index] + "\n") # 將目標字符串寫入文件
fo.close() # 關閉打開的文件