Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand the 'from' in Python [duplicate]

Tags:

python

glob

from glob import glob
from os.path import isfile
def countwords(fp):
   with open(fp) as fh:
       return len(fh.read().split())

print "There are" ,sum(map(countwords, filter(isfile, glob("*.txt") ) ) ), "words in the files."

in the first line, why don't this just simply import glob library?

Is there any reason for using "from glob" in front of "import glob"?

like image 779
rocksland Avatar asked May 04 '26 21:05

rocksland


2 Answers

If you write import glob, you would need to use glob.glob.

from glob import glob takes glob.glob and makes it available as just glob.

like image 85
ecatmur Avatar answered May 07 '26 11:05

ecatmur


>>> import glob
>>> dir(glob)
['__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 
 'fnmatch', 'glob', 'glob0', 'glob1', 'has_magic', 'iglob', 'magic_check', 
 'os', 're', 'sys']

You can see all of the functions in the glob module here, you may for example want an iterator version of glob and in that case you would use:

from glob import iglob
like image 38
jamylak Avatar answered May 07 '26 11:05

jamylak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!