2017-03-02 90 views
0

我試圖使用python搜索包含多個.txt文件的文件夾中的字符串。
我的目標是找到那些包含字符串的文件並將它們移動或重新寫入另一個文件夾中。 我曾嘗試是:移動/重寫與多個txt文件相匹配的文件夾中的字符串的txt文件

import os 

for filename in os.listdir('./*.txt'): 
    if os.path.isfile(filename):  
     with open(filename) as f: 
      for line in f: 
      if 'string/term to be searched' in line: 
       f.write 
       break 

可能有什麼不對這個,但是,當然,也不能弄明白。

+1

會發生什麼?應該發生什麼? – Dschoni

+0

和:'f.write'應該是'f.write(something)','something'是一個你想在文件中寫入的字符串。 – Dschoni

回答

0

os.listdir參數必須是路徑,而不是模式。您可以使用glob來完成這項任務:

import os 
import glob 

for filename in glob.glob('./*.txt'): 
    if os.path.isfile(filename):  
     with open(filename) as f: 
      for line in f: 
       if 'string/term to be searched' in line: 
        # You cannot write with f, because is open in read mode 
        # and must supply an argument. 
        # Your actions 
        break 
0

安東尼奧說,你不能爲f寫,因爲它是在讀模式下打開。 一個可能的解決方案,以避免問題如下:

import os 
import shutil 

source_dir = "your/source/path" 
destination_dir = "your/destination/path" 


for top, dirs, files in os.walk(source_dir): 
    for filename in files: 
     file_path = os.path.join(top, filename) 
     check = False 
     with open(file_path, 'r') as f: 
      if 'string/term to be searched' in f.read(): 
       check = True 
     if check is True: 
      shutil.move(file_path, os.path.join(destination_dir , filename)) 

請記住,如果你的source_dir或destination_dir包含一些「特殊字符」你必須把雙反斜線。

例如,這樣的:

source_dir = "C:\documents\test" 

應該

source_dir = "C:\documents\\test" 
相關問題