1、问题背景
一个目录下含有多个子目录,子目录下还有文件夹,其中有很多个txt文件。
2、请教问题
怎么才能把每个文本内容中,含有“小明”或“小红”或“小强”关键字的txt文件筛选出来?请注意,是“或”不是“和”。
3、想要达到的结果
一是移动到制定目录。二是删除筛选出的文件。需要分成两段代码。
万分万分感谢!
适合任意多级的目录
#####移动
import shutil
import os
import pandas as pd
paht1='D:/path1/' ##多层目录的首层目录
path2='D:/path2/' ##制定目录
##判断目标文件夹是否存在,如果不存在就新建一个
if not os.path.exists(path2):
os.makedirs(path2)
for root, dirs, files in os.walk(path1): ##遍历所有文件,root 表示目录,dirs 表示文件夹名,files 表示文件
for f in files: ##在文件中循环
if '.txt' in f:
with open(os.path.join(root, f),'r') as f1:
txt=f1.read()
if '小明' in txt or '小红' in txt or '小强' in txt:
shutil.move(os.path.join(root, f),path2+f)
##删除
import shutil
import os
import pandas as pd
paht1='D:/path1/' ##多层目录的首层目录
path2='D:/path2/' ##制定目录
##判断目标文件夹是否存在,如果不存在就新建一个
if not os.path.exists(path2):
os.makedirs(path2)
for root, dirs, files in os.walk(path1): ##遍历所有文件,root 表示目录,dirs 表示文件夹名,files 表示文件
for f in files: ##在文件中循环
if '.txt' in f:
with open(os.path.join(root, f),'r') as f1:
txt=f1.read()
if '小明' in txt or '小红' in txt or '小强' in txt:
os.remove(os.path.join(root, f))
一个目录下含有多个子目录,子目录里面还有文件夹么