Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #32778
| From | Terry Reedy <tjreedy@udel.edu> |
|---|---|
| Subject | Re: accepting file path or file object? |
| Date | 2012-11-05 13:30 -0500 |
| References | <CAF_E5JYQd5aPnjtpjiHVBpsro-85pV-4zQA9oaNdPUkhOkAZ9g@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3293.1352140232.27098.python-list@python.org> (permalink) |
On 11/5/2012 5:54 AM, andrea crotti wrote: > Quite often I find convenient to get a filename or a file object as > argument of a function, and do something as below: > > def grep_file(regexp, filepath_obj): > """Check if the given text is found in any of the file lines, take > a path to a file or an opened file object > """ > if isinstance(filepath_obj, basestring): > fobj = open(filepath_obj) > else: > fobj = filepath_obj > > for line in fobj: > if re.search(regexp, line): > return True > > return False > > > This makes it also more convenient to unit-test, since I can just pass > a StringIO. But then there are other problems, for example if I pass > a file object [it] is the caller that has to make sure to close the file > handle.. Which is as it should be. The caller should (normally) call your function within a with statement or might want to do other operations on the file before or after passing it to your grep_file. -- Terry Jan Reedy
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: accepting file path or file object? Terry Reedy <tjreedy@udel.edu> - 2012-11-05 13:30 -0500
csiph-web