温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2020-11-13 09:43:55 来源:亿速云 阅读:702 作者:小新 栏目:编程语言

这篇文章主要介绍怎样使用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批量查找文件并复制的所有内容,感谢各位的阅读!希望分享的内容对大家有帮助,更多相关知识,欢迎关注亿速云行业资讯频道!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI