2014-07-22 3 views
0

디렉토리의 모든 파일을 검색하고 일치하는 항목 (파일 내용의 특정 IP)이 있으면 다른 디렉토리의 새 파일에 해당 내용을 쓰려고합니다. 그리고 디렉토리의 모든 파일에 대해 이렇게하십시오. 지금까지이 파일을 가지고 있지만 새 파일에 한 줄만 씁니다. 너희들도 도와 줄 수 있니?파일에 일치하는 모든 줄을 쓰는 방법

import os, re 

wanted = ['10.10.10.10'] 
dir_list = os.listdir('D:\\path\\07') 

for i in dir_list: 
    n = open('D:\\path\\07\\'+i,'r') 
    m=n.readlines() 
    for line in m: 
     if any(wanted_word in line for wanted_word in wanted): 
      with open('Z:\\PYTHON\\Filtered-'+i,'w') as filtered_log: 
       filtered_log.write(line) 

나는 이것을 사용해 봤는데 아무런 오류도없고 아무런 결과도 없습니다.

import re, os 

regex = "(.*)10.10.10.10(.*)" 

dir_list = os.listdir('D:\\path\\07') 

for i in dir_list: 
    n = open('D:\\path\\07\\'+i,'r') 
    for line in n: 
     if re.match(regex, line): 
      with open('Z:\\PYTHON\\Filtered_'+i,'w') as filtered_log: 
       filtered_log.write(lines) 
+1

''도트를 탈출 한 것을 잊었습니까? – Unihedron

+0

필자는 파일을'w'로 열면 거기에 있던 파일을 잘라내서 열어서 추가 할 수 있도록 열어야한다고 말하고 싶습니다. – ZWiki

+0

점이 문제가되지 않습니다. 의도 한대로 쓰여졌다. 실제로 문제는 파일 모드입니다. 모든 것이 지금 작동합니다. 건배 user2599709 – Belial

답변

1

.는 정규 표현식에서 특수 문자입니다, 그래서 당신은 당신이 그것을 탈출 있는지 확인해야합니다

>>> import re 
>>> e = r'10\.10\.10\.10' 
>>> s = "There are some IP addresses like 127.0.0.1 and 192.168.1.1, but the one I want is 10.10.10.10 and nothing else" 
>>> s2 = "I only contain 192.168.0.1" 
>>> re.search(e, s) 
<_sre.SRE_Match object at 0x7f501fb771d0> 
>>> re.search(e, s2) 
이 어떤 코드로 일어나고있는 것은 당신이 선을 일치마다이

열려 파일의 내용을 삭제하는 쓰기 모드에서 다시 파일; 효과적인 결과는 서면의 마지막 줄에 불과합니다.

    다음

    import os 
    import re 
    
    e = r'10\.10\.10\.10' 
    
    base_directory = r'D:/path/07' 
    base_dir_out = r'Z:/Python/' 
    
    for f in os.listdir(base_directory): 
        with open(os.path.join(base_directory, f), 'r') as in_file, 
         open(os.path.join(base_dir_out, 'Filtered-{}'.format(f), 'w') as out: 
          for line in in_file: 
           if re.search(e, line): 
            out.write(line) 
    

    참고 :

    당신은 당신이 쓰기에 한 번만 파일을 열고, 당신은 당신의 대상 디렉토리에있는 모든 파일을 필터링 때 닫습니다 있는지 확인해야합니다

  1. Windows에서도 /을 사용할 수 있습니다.
  2. 파일 경로를 결합 할 때는 항상 os.path.join을 사용해야합니다.
1

파일을 열면 w으로 이전 파일이 잘립니다. 그 이유는 새 파일에 한 줄만 표시되기 때문입니다.

wanted = ['10.10.10.10'] 
dir_list = os.listdir('D:\\path\\07') 

for i in dir_list: 
    n = open('D:\\path\\07\\'+i,'r') 
    m=n.readlines() 
    n.close() 
    for line in m: 
     if any(wanted_word in line for wanted_word in wanted): 
      tempFile = 'Z:\\PYTHON\\Filtered-' + i 
      if exists(tempFile): 
       with open('Z:\\PYTHON\\Filtered-'+i,'a') as filtered_log: 
        filtered_log.write(line) 
      else: 
       with open('Z:\\PYTHON\\Filtered-'+i,'w') as filtered_log: 
        filtered_log.write(line) 
관련 문제