Home > Back-end >  Open multiple files with the same extension in a folder
Open multiple files with the same extension in a folder

Time:10-11

I want to open all files with the same extension (.dat) in the same directory.

This is my current code:

path = Path(".")  # current directory
extension = ".dat"
file_with_extension = next(path.glob(f"*{extension}"))
if file_with_extension:
    with open(file_with_extension, encoding='utf-8') as infile, open('462888.dat', 'w', encoding='utf-8') as outfile:
        for line in infile:
            if '462888' in line:
                outfile.write(line)

The problem with my current code is that it can only open and read one file with the extension (.dat). How do I read all of them?

CodePudding user response:

The result from path.glob(f"*{extension}") is actually an iterable, that you can iterate over and get each file name one by one, in a for loop.

This way, you should add a for loop over the filenames and open each one, read the lines (with another for loop), and write on the output file.

Something like this:

from pathlib import Path

path = Path(".")  # current directory
extension = ".dat"
with open('462888.dat', 'w', encoding='utf-8') as outfile:
  for filename in path.glob(f"*{extension}"): 
    with open(filename, encoding='utf-8') as infile:
      for line in infile:
        if '462888' in line:
            outfile.write(line)
    
  • Related