I am working on a code that searches a folder gets a specific part of the file name and adds 1 to a file counter. There are some files in tehre that have a special character that indicates that is is only half. I ahve got it to count the full ones but can not figure out a way to get the half ones to count. The special character that is in the names to inficate half is H. If someone could please help me figure this out it would help increase my production time.

def bedCount(pathname, bednumber):
    filecount = 0
    for file in os.listdir(pathname):
        if fnmatch.fnmatch (file, ''+bednumber+''):
            filecount = filecount+1
    return filecount
countbeds=bedCount(filestart, 'B')
print countbeds

I'am using different imports and python 3

import tkinter.filedialog as tk_FileDialog
from tkinter import*

fileCount = 0

for x in range(0,10)    #read as many as you want
    f = tk_FileDialog.askopenfile(mode='r')     #Or what file your trying to open
    fileContents = f.readlines(1)   #Or what lines you want to read
    if fileContents == 'H':
        fileCount += 0.5
    elif fileContents == 'h':
        fileCount += 0.5
    else:
        fileCount += 1

print "File count was", fileCount

This is if the first letter of the filename is the indicator otherwise regex required.

import os


def fileCheck(pathname):
    countB = 0
    countH = 0
    for file in os.listdir(pathname):
        if file[0] == 'B':
            countB += 1
        elif file[0] == 'H':
            countH += 1
        else:
            pass
    return countB, countH

Maybe more explicit and hence more pythonic? Unsure.

import os
def fileCheck(pathname):
    countB = 0
    countH = 0
    for file in os.listdir(pathname):
        if file.startswith('B'):
            countB += 1
        elif file.startswith('H'):
            countH += 1
        else:
            pass
    return countB, countH
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.