0

我有大约 100 个随机名称的文件夹,例如 1,2,3,4,...100。在这些文件夹中,我有包含一些字符串的文本文件。例如:sample.txt。

这些文本文件都具有相同的名称,但位于不同的文件夹中。我需要的是从这些文件夹中读取文件,并读取这些文件中的文本并打印出或保存这些文本文件的位置。

如果文件在我的密码中,我只知道如何从文件中读取行并在其中查找内容。我为此使用以下代码:

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

如何从文件夹中读取文件并记录这些文件夹的名称?

4

2 回答 2

1

您可以为此使用 os。例如:

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

这将为您提供列表中的所有子文件夹和文件。然后,您可以遍历列表以找到所需的子文件夹并重复该操作。

于 2016-12-23T00:04:04.137 回答
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

上面的代码对我有用。

于 2016-12-23T00:38:32.187 回答