Hardware Reference
In-Depth Information
DIGGING INTO THE CODE
glob.glob()
—what a funny name for a function. So funny that you have to
put it twice!
The name
glob
is used twice because the first one is the name of the module
(the
glob
module) that it was imported from at the top of your program. The
second use of
glob
is the name of the function
glob
inside the module
glob
.
But what does
glob
do, and why is it called
glob
?
It is simply short for the word “global command” and stems from the early days
of the design of the Unix operating system. You can read about the history
All it does is collect a list of files that match a pattern (or a
wildcard
). When you
use
glob.glob("*.csv")
Python searches the current directory in the com-
puters filing system, and generates a list of all the files that end in
".csv"
.
So, if you have the files
one.csv
,
two.csv
and
three.csv
in your
MyAdventures
folder, using
glob.glob("*.csv")
will return a Python list
that looks like this:
['one.csv', 'two.csv', 'three.csv']
Remember that the
for
loop will loop through all items in a list, which is why
these next lines of code are really useful:
for name in glob.glob("*.csv")
print(name)
A
wildcard
is a special character that can be used to select lots of similar names
or words. It's like a joker or a “wild card” in a pack of playing cards, it can represent
anything you want it to be.
In Python, the wildcard is often used to select lots of similarly named files in the
iling system, such as “all CSV iles. This can be done with
glob.glob(“*.
csv”)
, the
*
character marks the wildcard position, and
glob.glob()
will
match any file in the filing system that ends with the letters
.csv
.