erodr777
erodr777

Reputation: 23

How to remove lines from files in a folder?

I have a Python script that is able to remove lines in a file in a folder that contain certain keywords. It does this by creating a separate file and places it in a separate folder.

I would like to accomplish the same thing, but rather than do it on a per file basis I would like to apply it to all files within a specified folder. Here is what I have to accomplish this on a single file:

keywords = ['enable', 'password', 'secret', 'key', 'community']
file_name = str(input("Enter File Name:"))
with open(r"C:\Users\er\Desktop\\" + file_name) as oldfile, \
     open(r"C:\Users\er\Desktop\Clean_Files\\" + file_name, 'w') as newfile:
    for line in oldfile:
        if not any(keyword in line for keyword in keywords):
            newfile.write(line)

Does anyone know how to accomplish this?

Upvotes: 2

Views: 369

Answers (1)

lmiguelvargasf
lmiguelvargasf

Reputation: 69765

You need to use os.listdir(path='.'), use this loop, and then use it with the logic you already have:

import os

keywords = ['enable', 'password', 'secret', 'key', 'community']

for file_name in os.listdir('path\\to\\your\\directory'):
    with open(r"C:\Users\er\Desktop\\" + file_name) as oldfile, open(r"C:\Users\er\Desktop\Clean_Files\\" + file_name, 'w') as newfile:
        for line in oldfile:
            if not any(keyword in line for keyword in keywords):
               newfile.write(line)

Notice that if you don't pass a file to os.listdir(), it will use the current directory as path.

Alternatively, as mentioned by @pylang, you can use pathlib.Path("path/to/dir/").iterdir() instead of os.listdir('path\\to\\your\\directory').

Upvotes: 1

Related Questions