Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Re: accepting file path or file object?

Reply
Thread Tools

Re: accepting file path or file object?

 
 
Peter Otten
Guest
Posts: n/a
 
      11-05-2012
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 is the caller that has to make sure to close the file
> handle..
>
> So I'm thinking if it's not just worth to skip the support for file
> objects and only use the filenames, which seems a more robust and
> consistent choice..
>
> Any comment/suggestions about this?


I sometimes do something like this:

$ cat xopen.py
import re
import sys
from contextlib import contextmanager

@contextmanager
def xopen(file=None, mode="r"):
if hasattr(file, "read"):
yield file
elif file == "-":
if "w" in mode:
yield sys.stdout
else:
yield sys.stdin
else:
with open(file, mode) as f:
yield f

def grep(stream, regex):
search = re.compile(regex).search
return any(search(line) for line in stream)

if len(sys.argv) == 1:
print grep(["alpha", "beta", "gamma"], "gamma")
else:
with xopen(sys.argv[1]) as f:
print grep(f, sys.argv[2])
$ python xopen.py
True
$ echo 'alpha beta gamma' | python xopen.py - gamma
True
$ echo 'alpha beta gamma' | python xopen.py - delta
False
$ python xopen.py xopen.py context
True
$ python xopen.py xopen.py gamma
True
$ python xopen.py xopen.py delta
False
$


 
Reply With Quote
 
 
 
Reply

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off


Similar Threads
Thread Thread Starter Forum Replies Last Post
Re: accepting file path or file object? Cameron Simpson Python 0 11-05-2012 09:58 PM
Re: accepting file path or file object? Terry Reedy Python 0 11-05-2012 06:30 PM
accepting file path or file object? andrea crotti Python 2 11-05-2012 03:05 PM
Re: accepting file path or file object? Peter Otten Python 0 11-05-2012 01:47 PM
When did Windows start accepting forward slash as a path separator? Stephen Ferg Python 30 09-30-2003 04:22 AM



Advertisments
 



1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57