[英]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.