Python递归获取文件夹下面所有文件名字:
def getAllFiles(targetDir):
files = []
listFiles = os.listdir(targetDir)
for i in range(0, len(listFiles)):
path = os.path.join(targetDir, listFiles[i])
if os.path.isdir(path):
files.extend(getAllFiles(path))
elif os.path.isfile(path):
files.append(path)
return files
全部代码:
from shutil import copyfile
from sys import exit
import re
import time
import os
def getAllFiles(targetDir):
files = []
listFiles = os.listdir(targetDir)
for i in range(0, len(listFiles)):
path = os.path.join(targetDir, listFiles[i])
if os.path.isdir(path):
files.extend(getAllFiles(path))
elif os.path.isfile(path):
files.append(path)
return files
files = getAllFiles("E:\\anran_mail\\source_files\\allen-p")
for line in files:
line = line.strip()
old_name = line
line = line.split('\\')
print(line)
new_name = line[-2]+line[-1]
print(new_name)
line = str(line)
copyfile(old_name,"E:\\anran_mail\\mails\\"+str(new_name))
截图: