[英]Find files in a directory containing desired string in Python file and stored all that files into another folder
How can we identify XML files of desired labels in the same directory and then separate them into another directory, for example, I have Cat, Dog, Elephant, zebra dataset's XML files but I want to identify the "Cat" named tags in XML files and then I want all that XML files belonging to "cat" label to cut from that directory to paste it into another directory.我们如何在同一目录中识别所需标签的 XML 文件,然后将它们分开到另一个目录中,例如,我有猫,狗,大象,斑马数据集的 XML 文件,但我想识别 Z38301BB1093B936 文件中名为“猫”的标签然后我希望所有属于“cat”label 的 XML 文件从该目录中剪切以将其粘贴到另一个目录中。 I tried a lot to find out the way to get proper results with the help of parse commands.
在解析命令的帮助下,我尝试了很多方法来获得正确的结果。
import os
user_input = input('What is the name of your directory')
directory = os.listdir(user_input)
searching = input('What word are you trying to find?')
for fname in directory:
if os.path.isfile(user_input + os.sep + fname):
# Full path
f = open(user_input + os.sep + fname, 'r')
if searching in f.read():
print('found string in file %s' % fname)
else:
print('string not found')
f.close()
Here's an approach that uses glob
to find all xml files in the directory that contain the input word, then checks for the existence of the new directory and moves the files:这是一种使用
glob
查找包含输入单词的目录中的所有 xml 文件的方法,然后检查新目录是否存在并移动文件:
from glob import glob
import os
import shutil
directory = input('What is the name of your directory')
searching = input('What word are you trying to find?')
files = glob(f"{directory}/*{searching}*.xml")
if files:
# check if directory already exists
if not os.path.exists(searching):
os.makedirs(searching)
#move files to directory
for file in files:
shutil.move(file, directory)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.