2016-12-22 30 views
0

我有大約100個隨機名的文件夾,例如1,2,3,4 ,... 100。 在這些文件夾中,我有一些文本文件,其中包含一些字符串。 例如:sample.txt。從文件夾中讀取文本文件並保存該文件夾的名稱(如果在文本文件中找到了特定的字符串) - Python

文本文件都具有相同的名稱,但位於不同的文件夾中。 我需要的是從這些文件夾中讀取文件,並閱讀這些文件中的文本,並打印出或保存這些文本文件的位置。

我只知道如何讀取文件中的行,如果它位於我的密碼中並查找其中的內容。 我用下面的代碼:

with open(r'Example.txt', 'r') as infile_txt: 
    for line in infile_txt: 
     if r"sample" in line: 
      print line 

我如何可以讀取文件夾內的文件和記錄這些文件夾的名稱?

回答

1

你可以使用操作系統。例如:

import os 
list_downloads = os.listdir("C:/Users/user/Downloads") 

這會爲您提供列表中的所有子文件夾和文件。然後,您可以遍歷列表以查找所需的子文件夾並重復該操作。

+0

謝謝。我不確定導入和格式。這肯定有幫助。 –

0
import os 
import re 
from os.path import join, getsize 

with open('output.txt','w') as out_file: 
    for root,subFolders, files in os.walk(r"C:\Users\USER007\Desktop\Python Scripts\Reading metadata\files"): 
     if r'MetaData.txt' in files: 
      with open(os.path.join(root, 'MetaData.txt'), 'r') as in_file: 
       for lines in in_file: 
        if r'THIS' and r'THAT' and r'THOSE' in lines: 
         print root 

上面的代碼適用於我。

相關問題