What is the glob2 module?

13,133

Solution 1

from glob docs

"The glob module finds all the pathnames matching a specified pattern(...)"

i skip the imports import glob2 and from datetime import datetime

get all the filenames in the directory where filename is any and it is extension is text

filenames = glob2.glob("*.txt")

open new file which name is current datetime in the format as specified in the strftime and open it with write access as variable 'file'

with open(datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f")+".txt", 'w') as file:

for each filenames in found files which names / paths are stored in filenames variable...

for filename in filenames:   

with the filename open for read access as f:

with open(filename, "r") as f:

write all content from f into file and add \n to the end (\n = new line)

file.write(f.read() + "\n")

Solution 2

I also saw "glob2"-module used in a kaggle-notebook and researched my own answer in what is the difference to "glob".

All features of "glob2" are in the current included "glob"-implementation of python.

So there is no reason to use "glob2" anymore. As for what glob does in general, BlueTomato already provided a nice link and description.

Share:
13,133

Related videos on Youtube

Tomerikoo
Author by

Tomerikoo

Updated on June 04, 2022

Comments

  • Tomerikoo
    Tomerikoo about 2 years
    import glob2
    from datetime import datetime
    
    
    
    filenames = glob2.glob("*.txt")
    with open(datetime.now().strftime("%Y-%m-%d-%H-%M-%S-%f")+".txt", 'w') as file:
        for filename in filenames:       
            with open(filename, "r") as f:
                file.write(f.read() + "\n")
    

    I was working in python and came across this name glob, googled it and couldn't find any answer, what does glob do, why is it used for?

    • Jean-François Fabre
      Jean-François Fabre over 6 years
      if it works, it scans all text files from curent dir and concatenate their contents on a big, dated file.
    • Jean-François Fabre
      Jean-François Fabre over 6 years
      if you ask me, the flaw is that running this program again uses the output from prior execution since the extension & dir are the same for input & output
    • Matthias
      Matthias over 6 years
      glob2 is an external library.
    • Admin
      Admin over 6 years
      I am new to python i really dont have any idea about glob2, filenames = glob2.glob("*.txt") what does the above code does.. can someone explain this line by line...
    • Wolverine313
      Wolverine313 over 5 years
      hmmm... I see someone is doing the python mega course. ;)
  • Gigi
    Gigi over 3 years
    Is this still the case / is glob2 outdated?
  • Stefan
    Stefan over 3 years
    The last version is from June 2019 ... I would go for the python-included "glob".