Python - Opening successive Files without physically opening every one -
if read number of files in python 3.2, 30-40, , want keep file references in list
(all files in common folder)
is there anyway how can open files respective file handles in list, without having individually open every file via file.open() function
this simple, use list comprehension based on list of file paths. or if need access them 1 @ time, use generator expression avoid keeping forty files open @ once.
list_of_filenames = ['/foo/bar', '/baz', '/tmp/foo'] open_files = [open(f) f in list_of_filenames]
if want handles on files in directory, use os.listdir
function:
import os open_files = [open(f) f in os.listdir(some_path)]
i've assumed simple, flat directory here, note os.listdir
returns list of paths file objects in given directory, whether "real" files or directories. if have directories within directory you're opening, you'll want filter results using os.path.isfile
:
import os open_files = [open(f) f in os.listdir(some_path) if os.path.isfile(f)]
also, os.listdir
returns bare filename, rather whole path, if current working directory not some_path
, you'll want make absolute paths using os.path.join
.
import os open_files = [open(os.path.join(some_path, f)) f in os.listdir(some_path) if os.path.isfile(f)]
with generator expression:
import os all_files = (open(f) f in os.listdir(some_path)) # note () instead of [] f in all_files: pass # open file here.
in cases, make sure close files when you're done them. if can upgrade python 3.3 or higher, recommend use exitstack
1 more level of convenience .
Comments
Post a Comment