![](/img/trans.png)
[英]Reading a text file from within a folder and saving the name of the folder if a particular string is found in the text file - Python
[英]To print a particular folder name in python?
我已经在python中制作了一个脚本,该脚本扫描了所有文件夹和子文件夹,然后打印了所有以Hello开头的文件夹和子文件夹。
现在,我需要执行一项更改,即应该可以打印任何带有单词Hello的文件夹。 像单词一样可以是hiHello或abcHelloxyz。 因此,还必须打印该文件夹。 我猜想需要使用grep命令。
import os
if os.path.isdir('/'):
for root, dirs, files in os.walk('/'):
for name in dirs:
if name.startswith(("hello")):
print ("\n\nFile Name: "+ name)
name = os.path.abspath(os.path.join(root, name)
)
print ("Path :"+name)
您可以使用dirname
中的'Hello' in dirname
来测试'Hello'
是目录名中的子字符串:
In [1]: dirname = 'hiHello'
In [3]: 'Hello' in dirname
Out[3]: True
In [4]: dirname.startswith('Hello')
Out[4]: False
您可以尝试使用正则表达式:
dirlist = ['somedir', 'Hello', 'dirHello', 'hiHello', 'abcHello', 'randdir']
hellodir = re.findall('.*Hello.*', '\n'.join(dirlist))
print hellodir
>>['Hello', 'dirHello', 'hiHello', 'abcHello']
我完成了更改。 我需要将输出存储在特定的文件夹中。 我应该使用shutil.move命令吗?
导入操作系统
如果os.path.isdir('/'):用于root,dirs,则文件在os.walk('/'):用于dirs中的名称:if(name.find((“ hello”))!=-1) :打印(“ \\ n \\ n文件名:” +名称)名称= os.path.abspath(os.path.join(root,name))
打印(“路径:” +名称)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.