2016-10-11 47 views
-1

我想在文件夾中的許多文件中搜索「單詞」。搜索文件夾中的所有文件

我已經:

route=os.listdir("/home/new") 
for file in route: 

這不起作用:

f = open ('' , 'r') 
for line in f : 

我嘗試這樣做:

for file in route: 
    f = open(file, 'r') 
    for line in f: 
     if word in line: 
      print(file) 
      break 

,但我有一個錯誤:

f=open(file ,'r') 
IOError: [Errno 2] No such file or directory: file.txt 

當我刪除file.txt,下一個文件時,我收到相同的錯誤。

+0

那麼,那只是罕見的第一步。你是否已經對文件部分進行了實際搜索? –

+0

你是什麼意思「它不工作」?什麼是輸出? –

+1

「open()」的第一個參數必須是文件名(即你的案例中的「file」),而不是空字符串''''''你有。之後,瀏覽該文件,並通過使用諸如「if」字樣的「行:#做某事」來搜索「行」中「'」字「''的出現。 – Schmuddi

回答

0
for file in filelist:  
    f = open(file,"r") 
    data = f.read() 
    rows = data.split("\n") 
    count = 0 
    full_data = [] 
    for row in rows: 
     split_row = row.split(",") 
     full_data.append(split_row) 
    for each in full_data: 
     if re.search("word", each) is not None: 
      count += 1 

這樣的事情,雖然你的問題是根本就沒有指定有關是否要算,返回那裏詞發現,改變字的東西等等,以便隨時爲您認爲合適的

進行編輯

(此代碼爲格式爲* .csv你可能會說)

-1

你已經擁有了下去主要是:

for file in route: 
    f = open(file, 'r') 
    for line in f: 
     if word in line: 
      print(file) 
      break 
0

沿着這些方向怎麼樣?

import os 

folderpath = "/.../.../foldertosearch" 
word = 'giraffe' 

for(path, dirs, files) in os.walk(folderpath, topdown=True): 
    for filename in files: 
     filepath = os.path.join(path, filename) 
     with open(filepath, 'r') as currentfile: 
      for line in currentfile: 
       if word in line: 
        print(
         'Found the word in ' + filename + ' in line ' + 
         line 
        ) 
相關問題