簡體   English   中英

循環瀏覽Python中的文件夾以及包含字符串的文件

[英]Loop through folders in Python and for files containing strings

我是python的新手。 我需要遍歷給定目錄的子目錄,並返回包含特定字符串的所有文件。

for root, dirs, files in os.walk(path):
    for name in files:
        if name.endswith((".sql")):
            if 'gen_dts' in open(name).read():
                print name

這是我最接近的。

我得到的語法錯誤是

Traceback (most recent call last):
  File "<pyshell#77>", line 4, in <module>
    if 'gen_dts' in open(name).read():
IOError: [Errno 2] No such file or directory: 'dq_offer_desc_bad_pkey_vw.sql'

“ dq_offer_desc_bad_pkey_vw.sql”文件中不包含“ gen_dts”。

我先感謝您的幫助。

之所以出現該錯誤,是因為您試圖打開name ,它只是文件 ,而不是完整的相對路徑。 您需要做的是open(os.path.join(root, name), 'r') (我添加了此模式,因為這是一種很好的做法)。

for root, dirs, files in os.walk(path):
    for name in files:
        if name.endswith('.sql'):
            filepath = os.path.join(root, name)
            if 'gen_dts' in open(filepath, 'r').read():
                print filepath

os.walk()返回一個生成器,該生成器為您提供元組,例如(root, dirs, files) ,其中root是當前目錄,而dirsfiles分別是位於根目錄中的目錄和文件的名稱。 請注意,它們是名稱 ,而不是路徑。 確切地說,它們是該目錄/文件對於當前根目錄的路徑,這是另一種說法。 另一種思考的方式是,目錄和文件中的dirsfiles永遠不會包含斜線。

最后一點; 根目錄路徑始終以您傳遞給os.walk()的路徑開頭,無論該路徑是否相對於當前工作目錄。 因此,對於os.walk('three') ,第一個元組的root將為'three' (對於os.walk('three/') ,它將為'three/' )。 對於os.walk('../two/three') ,它將是'../two/three' 對於os.walk('/one/two/three/') ,它將是'/one/two/three/' ; 第二個可能是'/one/two/three/four'

文件只是文件名。 您需要先將路徑添加到中,然后再打開它們。 使用os.path.join。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM