qwerty ayyy
qwerty ayyy

Reputation: 385

Python process text files in a loop

I have 10 text files in the same folder. I want to process each text file individually in a for loop.

def qwerty():
    with open('file.txt') as f:
       dicts = {}
       for words in f:
          split_words = reg.finditer(words)
          for line in split_words:
             group1 = line.group(1)
             if group1 not in dicts:
                dicts[group1] = 1
             else:
                dicts[group1] += 1 
     return dicts

This is my code to process the individual text file. How do I run a loop that would process all the text files I have one by one? So the amount of text files correspond to the number of iterations in the for loop.

Upvotes: 0

Views: 139

Answers (2)

tdelaney
tdelaney

Reputation: 77407

You can enumerate the files in a folder and use that in a for loop

import os
from glob import glob

def qwerty(folder_path="."):
    for filename in glob(os.path.join(folder_path, "*.txt")):
        ... do your processing

Upvotes: 0

ZdaR
ZdaR

Reputation: 22974

You may use os module to iterate over all the files in current directry and filter only the txt files as :

import os

for file_name in os.listdir("./"):
    if file_name.endswith(".txt"): # Add some other pattern if possible
        # Call your method here

Your current directory would contain some other files as well, which may not get filtered, So it would be a better idea to move the txt files to a separate location.

Upvotes: 2

Related Questions