Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This should do what you need. Put file with this code in the directory where you have your <code>.log</code> files, replace <code>KEYWORD</code> with what you are actually looking for, and run it.</p> <pre><code>import os theKeyword = 'KEYWORD' directory = '.' with open('output.csv', 'w') as out: for file in os.listdir(directory): if file.endswith(".log"): with open(file, 'r') as f: for line in f: if theKeyword in line: out.write(line) </code></pre> <p>As suggested, you can use <a href="http://docs.python.org/2/library/glob.html" rel="nofollow"><code>glob</code></a> instead of <a href="http://docs.python.org/2/library/os.html#os.listdir" rel="nofollow"><code>os.listdir</code></a>:</p> <pre><code>from glob import glob with open('output.csv', 'w') as out: for file in glob('*.log'): with open(file, 'r') as f: for line in f: if 'KEYWORD' in line: out.write(line) </code></pre> <p>The code can be even a bit simpler if you use <a href="http://docs.python.org/2/library/fileinput.html" rel="nofollow"><code>fileinput</code></a> module:</p> <pre><code>from glob import glob import fileinput with open('output.csv', 'w') as out: for line in fileinput.input(glob('*.log')): if 'KEYWORD' in line: out.write(line) </code></pre> <p>Another variation of the 'grep in Python' thing:</p> <pre><code>from glob import glob import fileinput with open('output.csv', 'w') as out: out.writelines(line for line in fileinput.input(glob('*.log')) if 'KEYWORD' in line) </code></pre> <p>In the above snippet, if you remove <code>fileinput.input</code>'s argument, then it will process <code>sys.argv[1:]</code>, so you can run your script with file names as parameters.</p> <p>In case you'd like to search for files recursively in subdirectories of a directory, you should have a look at <a href="http://docs.python.org/2/library/os.html#os.walk" rel="nofollow"><code>os.walk</code></a> function.</p> <p>If you have a Linux/Unix/Mac box, or if you have <a href="http://www.cygwin.com/" rel="nofollow">Cygwin</a> installed on a Windows box, the same can be achieved a bit easier using shell tools:</p> <pre><code>$ cat *.log| grep KEYWORD &gt;output.csv </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload