需求:
1.获取当前子文件中名字包含特定名称的CSV文件
2.将获取文件复制到新建文件夹中,文件夹名称为boxdata加上当前年月日
3.生成日志文件,列出被复制的文件及文件总数
# 导入文件处理相关库
import os
import shutil
from datetime import datetime
now = datetime.now() # 获得当前时间
timestr = now.strftime("%Y%m%d")
timestr2 = now.strftime("%Y%m%d%H%M%S")
timestr3 = now.strftime("%Y-%m-%d %H:%M:%S")
print('年月日:', timestr)
dir = os.getcwd() + '\boxdata' + timestr # os.getcwd()获得当前执行目录
if os.path.exists(dir): # 看文件夹是否存在
print('文件夹已存在')
else: # 如果不存在
os.makedirs(dir) # 则创建文件夹
t = open("keyword.txt") #获取同目录下keyword文件中的关键字,以检索文件名
s=t .read()
#ls = t.split() #从特殊符号分隔的文件中读入数据则可以用ls = f.split("$")
#f.close()
keyword=str(s) #获取文件中关键字,生成字符串
existfile = [] #创建一个空列表
def eachfile(filepath):
pathdir = os.listdir(filepath) #返回目录条目列表
#字符串遍历目录下条目,s是文件名
for s in pathdir:
newdir = os.path.join(filepath, s) # 将文件名s加入到当前文件路径后面
if os.path.isfile(newdir): # 如果是文件
if os.path.splitext(newdir)[1] == ".csv": # 选择文件是".csv"后缀的
if keyword in newdir:
existfile.append(newdir) #将符合关键字的路径和文件加入列表
elif os.path.isdir(newdir): # 如果是路径
eachfile(newdir) # 递归
return existfile
fp = str(os.getcwd()) #返回程序的当前路径,生成字符串赋值fp
print (fp) #输出路径
os.chdir(fp) #修改当前程序的操作路径
f = eachfile(fp) #eachfile函数返回了existfile列表,f是当前路径列表
#计数遍历,len(f)返回集合f的元素个数
for i in range(len(f)):
print(f[i]) #输出集合f的第i个元素
print(len(f)) #输出集合F的元素个数
#计数遍历
for i in range(len(f)):
pcm_file=f[i]
path_0 = os.path.split(f[i])[0] #返回目录路径和文件名的元组,0是路径
path_1 = os.path.split(f[i])[1] #返回目录路径和文件名的元组,1是文件名
print(path_1) #输出文件名
oldname = path_0 + '\' + path_1 #旧路径和文件名
newname = dir + '\' + path_1 #新路径和文件名
shutil.copyfile(oldname,newname) #用shutil模块复制文件
logname="log."+str(timestr2)+".txt" #建立txt文件作为log日志
print(str(i) + '\' + str(len(f)))
filelist=os.listdir(dir) #返回一个列表,包含当前目录的条目名称
set1 = set(filelist) #创建集合
with open(logname, 'w') as g: # 设置文件对象,将内容输出到文件中,'w'是覆盖写模式
for i in filelist:
print(i,file = g) #利用遍历循环,向列表中添加数据
print('',file = g) #输出一个文件名后换行
print("Copy File Count:"+str(len(set1)),file = g) #输出复制文件总数
print("Copy File Time:"+str(timestr3),file = g) #输出复制文件的时间
为方便用户使用,最后用PyInstaller库的功能将py文件生成了exe文件。
关键字文件keyword.txt放在同一目录下。
本人很长时间没碰代码了,初学python,还是第一次发文章。
代码功能还有很多不会实现,比如:当拷贝文件重复时自动终止了,却没有报错提示。
拜托各位有经验的大牛不吝赐教,看看怎么优化和提升,谢谢~



