Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>This is simple, just use a list comprehension based on your list of file paths. Or if you only need to access them one at a time, use a generator expression to avoid keeping all forty files open at once.</p> <pre><code>list_of_filenames = ['/foo/bar', '/baz', '/tmp/foo'] open_files = [open(f) for f in list_of_filenames] </code></pre> <p>If you want handles on all the files in a certain directory, use the <a href="http://docs.python.org/2/library/os.html#os.listdir" rel="nofollow"><code>os.listdir</code></a> function:</p> <pre><code>import os open_files = [open(f) for f in os.listdir(some_path)] </code></pre> <p>I've assumed a simple, flat directory here, but <strong>note</strong> that <code>os.listdir</code> returns a list of paths to all file objects in the given directory, whether they are "real" files or directories. So if you have directories within the directory you're opening, you'll want to filter the results using <code>os.path.isfile</code>:</p> <pre><code>import os open_files = [open(f) for f in os.listdir(some_path) if os.path.isfile(f)] </code></pre> <p>Also, <code>os.listdir</code> only returns the bare filename, rather than the whole path, so if the current working directory is not <code>some_path</code>, you'll want to make absolute paths using <code>os.path.join</code>.</p> <pre><code>import os open_files = [open(os.path.join(some_path, f)) for f in os.listdir(some_path) if os.path.isfile(f)] </code></pre> <hr> <p>With a generator expression:</p> <pre><code>import os all_files = (open(f) for f in os.listdir(some_path)) # note () instead of [] for f in all_files: pass # do something with the open file here. </code></pre> <p>In all cases, <strong>make sure you close the files when you're done with them</strong>. If you can upgrade to Python 3.3 or higher, I recommend you use an <a href="http://docs.python.org/3.4/library/contextlib.html#contextlib.ExitStack" rel="nofollow"><code>ExitStack</code></a> for one more level of convenience .</p>
    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