如何在目录中打开多个文件

时间:2016-08-17 08:44:05

标签: file python-3.x

我需要在python3中构建一个简单的脚本,在目录中打开更多文件,看看这些文件中是否有关键字。

目录中的所有文件都是这样的:" f * .formatoffile" (*留一个随便的号码)

示例:

f9993546.txt
f10916138.txt
f6325802.txt

很明显我只需要打开txt文件。

提前致谢!

最终剧本:

import os

Path = "path of files"
filelist = os.listdir(Path)
for x in filelist:
    if x.endswith(".txt"):
        try:
            with open(Path + x, "r", encoding="ascii") as y:
                for line in y:
                    if "firefox" in line:
                        print ("Found in %s !" % (x))
        except:
            pass

1 个答案:

答案 0 :(得分:2)

这应该可以解决问题:

import os
Path = "path of the txt files"
filelist = os.listdir(Path)
for i in filelist:
    if i.endswith(".txt"):  # You could also add "and i.startswith('f')
        with open(Path + i, 'r') as f:
            for line in f:
                # Here you can check (with regex, if, or whatever if the keyword is in the document.)