python如何批量查找文件并复制

516次阅读
没有评论

大家在写文档的时候,如果是遇到同一个信息,只需要复制粘贴,不需要重新写的时候,一般都会怎么做呢?小编先说下自己是怎么做的吧,我会先找到那篇文档内容,然后搜索我想要的内容,最后在复制粘贴过去,这个是直接在word上显示的,那如果想把整个流程在我们的代码上呈现,要怎么做?

直接上代码演示:

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如何批量查找文件并复制

好啦,大家在准备阶段时候,可以像小编演示的那样,将word文档作为一个流程模块,然后在带入学习编码,相信大家很容易掌握上述内容的哦~

神龙|纯净稳定代理IP免费测试>>>>>>>>天启|企业级代理IP免费测试>>>>>>>>IPIPGO|全球住宅代理IP免费测试

相关文章:

版权声明:wuyou2021-05-31发表,共计2074字。
新手QQ群:570568346,欢迎进群讨论 Python51学习