-3

I have the need to search a directory and display the number of text (*.txt) files. In researching, I am fairly certain I can use glob and os, but am at a bit of a loss on how to even start.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

2 Answers2

1

You can use os.listdir

import os
txtFiles = 0
for file in os.listdir("/dir"):
    if file.endswith(".txt"):
        txtFiles +=1

Hope this helps,

albciff
  • 18,112
  • 4
  • 64
  • 89
-1

I would try something along the lines of this:

import glob
import os

def fileCount():
    myFiles = dict()
    directory = "C:\somefolder\someotherfolder"

    for file in glob.glob("*"):
        if os.path.isfile(file):
            name, extension = os.path.splitext(file)
            myFiles[extension] = myFiles.get(extension, 0) + 1
            print(os.getcwd())
            os.chdir(directory)
            print('after chdir', os.getcwd())

    return myFiles

if __name__ == "__main__":
    files = fileCount()
    print(files)

The line for file in glob.glob("*"): will read all files in the specified directory. The line name, extension = os.path.splitext(file) will split out the file name and the extension into two objects, but only if the object is a file (as opposed to another folder).

Hope this helps

Trisped
  • 5,705
  • 2
  • 45
  • 58
Rich
  • 1
  • 1