怎样使用python批量查找文件并复制

这篇文章主要介绍怎样使用python批量查找文件并复制,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!

让客户满意是我们工作的目标,不断超越客户的期望值来自于我们对这个行业的热爱。我们立志把好的技术通过有效、简单的方式提供给客户,将通过不懈努力成为客户在信息化领域值得信任、有价值的长期合作伙伴,公司提供的服务项目有:主机域名、虚拟空间、营销软件、网站建设、大化网站维护、网站推广。

直接上代码演示:

1、输入一个文件夹路径:

搜索此路径下以及子路径下所有以py文件结尾的文件。并存放到列表中。另外,加上一定的异常的处理,提高代码的健壮性。

要求使用两种方法实现:

1、 使用递归

2、 使用python模块里的方法

import os
import os.path#存储py文件
list_total = []#存储其他类型文件
list_qita = []#文件夹路径
def folder_path(path):#找到当前文件夹下面的文件和文件夹
list = os.listdir(path#遍历每个文件和文件夹
for n in list:
old_path = os.path.join(path,n)
index = n.rfind(".")
if os.path.isfile(old_path) and n[index+1:]=="py":
list_total.append(n)
elif os.path.isdir(old_path):
mm = old_path#递归调用
folder_path(mm)
else:
list_qita.append(n)#主函数
def main():
m = input("请输入文件夹的路径:").strip()
folder_path(m)
print()
print("py文件有:",end="")
print(list_total)
print()
print("其他文件有:",end="")
print(list_qita)
print()#入口
main()
Python之文件的搜索以及复制
2、完成文件的复制粘贴
要求,模拟windows里的实现。
import os
import os.path#完成文件路径分割
def file_path():#C:\Users\Administrator\Desktop\a\a.txt
path_old = input("请输入文件的路径:").strip()#文件名+后缀
path_index = path_old.rindex('\\')
path_dir = path_old[:path_index]#path_name = path_old[path_index+1:]
lists = os.listdir(path_dir)
print(lists)#文件后缀
index = path_old.rindex(".")
dir = path_old[:index]
name = path_old[index:]#文件名a
filename = path_old[path_index+1:index]
if len(lists)==1:
path_new = dir + " - 副本" + name
else:
num = len(lists)
while num < 20:
if (filename +" - 副本" + name) not in lists:
path_new = dir + " - 副本" + name
elif (filename +" - 副本 " + "(" + str(num) + ")" + name) in lists:
n = 2
while n < len(lists):
if (filename +" - 副本 " + "(" + str(n) + ")" + name) in lists:
 
n += 1
else:
path_new = dir + " - 副本 " + "(" + str(n) + ")" + name
break
else:
path_new = dir + " - 副本 " + "(" + str(num) + ")" + name
num += 1
break
copy_and_paste_the_files(path_old,path_new)#文件复制
def copy_and_paste_the_files(old_path,new_path):
old_file = open(old_path,"rb")
new_file = open(new_path,"wb")
while True:
content = old_file.read(1024*1024)
if content:
new_file.write(content)
else:
print("文件复制完成!!!")
break
old_file.close()
new_file.close()#主程序
def main():
file_path()#程序入口
main()

最后运行效果:

怎样使用python批量查找文件并复制

以上是怎样使用python批量查找文件并复制的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注创新互联行业资讯频道!

网站标题:怎样使用python批量查找文件并复制
网页路径:https://www.cdcxhl.com/article28/jssdjp.html

成都网站建设公司_创新互联,为您提供品牌网站设计外贸建站建站公司虚拟主机网站建设标签优化

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

h5响应式网站建设