Home > front end >  How to count one by one how many files start with a word inside a folder (without using the os libra
How to count one by one how many files start with a word inside a folder (without using the os libra

Time:09-26

This is my code, but it is missing the part where it counts the files, still try to use startswith() instead of regex, maybe it is a more direct solution in this case

from pathlib import Path

def process_audio_files(file_name):

    #Edit the file
    transcription = file_name   "edited"
    
    return transcription
    

audio_chunks_path = "audio_chunks/"
names_structure = "chunk_"

#initializes the counter variable assuming that within the directory there may not be any files beginning with that word
n = 0
transcription = ""

if(audio_file.startswith(names_structure)): n  = 1

#once all the files have been accounted for
for i in n:
   file_name = audio_chunks_path   names_structure   str(i)   ".mp3"
   
   transcription = process_audio_files(file_name)
   print(transcription)

   Path(file_name).unlink() #delete this chunk audio file

For this for loop to work I must know what the value of n is, and for that I must know how many files are inside that directory, and therein lies the problem.

In the directory there is an unknown number of files that start with that word, so the value of the variable n will also be unknown

audio_chunks/chunk_0.mp3
audio_chunks/chunk_1.mp3
audio_chunks/chunk_2.mp3
...
audio_chunks/chunk_n.mp3

CodePudding user response:

If you want to count the number of files, you can do:

n = sum(1 for _ in Path("audio_chunks").glob("chunk_*.mp3"))

However, if you want to find the files and delete them you can just use the same glob function and do something like:

for chunk_file in Path("audio_chunks").glob("chunk_*.mp3"):
    transcription = process_audio_files(chunk_file)
    print(transcription)
    chunk_file.unlink()
  • Related