Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You can do it with a loop:</p> <p>import sys</p> <pre><code>def input_files(fd, word): """return the occurences of `word` in a file""" s = 0 for lines in fd: if word in lines: s += lines.count(word) return s if __name__ == '__main__': word = raw_input('Enter the word you want to search: ') total = 0 for filename in sys.argv[1:]: try: print("Searching for %s in %s..." % (word, filename)) with open(filename, "r") as fd: found = input_files(fd, word) total += found print("\t... found %i occurence(s)\n" % found) except IOError: print("\t... cannot open %s !" % filename) print("\nTotal: %i occurences" % total) </code></pre> <p>It will process all the files passed as arguments to your script...</p> <hr> <h3>Explanations:</h3> <p><code>sys.argv</code> is the variable containing the arguments passed to a script <em>via</em> the command line.</p> <p>For instance, if you execute the command <code>python my_script.py foo bar</code> the <code>sys.argv</code> variable in <code>my_script.py</code> will contain <code>["my_script.py", "foo", "bar"]</code>.</p> <p>As you can see, the first element of <code>sys.argv</code> is the name of the script itself, so we have to skip it (<code>sys.argv[1:]</code> means <em>« all items of <code>sys.argv</code> starting from index 1 »</em>, the item 0 is skipped).</p> <p>So in the script above, all the files passed as arguments to the script will be processed. Of course, if one of the file doesn't exists, it will fail.</p> Sources <ul> <li><a href="http://docs.python.org/library/sys.html?highlight=sys.argv#sys.argv" rel="nofollow">sys.argv</a></li> <li><a href="http://docs.python.org/library/stdtypes.html#typesseq" rel="nofollow">sequence types</a></li> </ul>
    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. 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