3
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"?

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
rocksland
  • 163
  • 2
  • 4
  • 8

6 Answers6

5

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.

ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • 2
    Agreed. I use the "from" keyword mostly for convenience, but sometime it's necessary in order to avoid name clashes. – djf Aug 08 '12 at 13:48
4
>>> 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
jamylak
  • 128,818
  • 30
  • 231
  • 230
3

if you use import glob, for the function glob("*.txt"), you have to write glob.glob("*.txt").

basically, the first glob in the from glob import glob is the name of the module, while the second one is the name of the function.

Yulong
  • 1,529
  • 1
  • 17
  • 26
2

from glob import glob will import glob attribute of glob module when import glob will import whole module

Daniil Ryzhkov
  • 7,416
  • 2
  • 41
  • 58
2

This link seemed to explain all of the different variations quite well:

http://effbot.org/zone/import-confusion.htm

The bottom line is that importing a specific thing from a module gives you a direct reference to ONLY that thing and not the whole module.

JerseyMike
  • 849
  • 7
  • 22
1

When you have import glob, you import all the functions from that module. When you have from xyz import abc, you're only importing the abc function from the xyz module. In this case, you're importing the glob function from the glob module.

This way, in the Python code, if you want to use the glob function, instead of writing glob.glob, you only have to write glob.

Di Zou
  • 4,469
  • 13
  • 59
  • 88