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

问题描述:

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

所有目录中的文件是这样的: “F * .formatoffile”(*为休闲号码保持)

例子:

f9993546.txt 
f10916138.txt 
f6325802.txt 

Obviusly我只需要打开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

你可能想打开一个文件后,其他检查它。 谷歌“循环目录python”,它会告诉你如何,然后发布你的代码,如果你卡住了 – 576i

+2

如果它总是相同的目录,你可以尝试查看['glob.glob'](https:/ /docs.python.org/3/library/glob.html#glob.glob)。 –

+0

解决了。不管怎么说,还是要谢谢你! – Sperly1987

这应该做的伎俩:

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.) 
+0

我会检查它是否有效 – Sperly1987

+0

我试过了,出现了问题。该脚本是好的,但我只是意识到txt文件都是不同的编码,实际上它说我:[code] UnicodeDecodeError:'utf-8'编解码器无法解码位置5637字节0xe7:无效的连续字节[/ code]有没有办法强制编码的所有组合,直到脚本找到合适的编码? – Sperly1987

+0

我解决了!我只是使用“ascii”,它似乎是最常用的编码,然后我添加了一个try-except,并在2秒内找到了我正在寻找的文件!再次感谢。我会在主文章上发布最终脚本 – Sperly1987