Q:

How to loop through each file in a folder, do some action to the file and save output to a file in another folder Python

I have a folder with multiple files like so:

1980
1981
1982

In each of these files is some text.  I want to loop through each of these files and do some operation to each file then save the edited file to another folder and move onto the next file and so on.  The result would be that I have the original folder and then another folder with the edited version of each file in it like so:

1980_filtered
1981_filtered
1982_filtered

Is it possible to do this? 
Currently I have some code that loops through the files in a folder, does some filtering to each file and then saves all the edits of each file into one massive file.  Here is my code:
import os
input_location = 'C:/Users/User/Desktop/mini_mouse'
output_location = 'C:/Users/User/Desktop/filter_mini_mouse/mouse'
for root, dir, files in os.walk(input_location):
    for file in files:
        os.chdir(input_location)
        with open(file, 'r') as f, open('NLTK-stop-word-list', 'r') as f2:
            mouse_file = f.read().split()  # reads file and splits it into a list
            stopwords = f2.read().split()
            x = (' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords)))
            with open(output_location, 'a') as output_file:
                output_file.write(x)

Any help would be greatly appreciated! 

A:

You need to specify what each new file is called.  To do so, Python has some good string formatting methods.  Fortunately, your new desired file names are easy to do in a loop
import os
input_location = 'C:/Users/User/Desktop/mini_mouse'
output_location = 'C:/Users/User/Desktop/filter_mini_mouse/mouse'
for root, dir, files in os.walk(input_location):
    for file in files:
        new_file = "{}_filtered.txt".format(file)
        os.chdir(input_location)
        with open(file, 'r') as f, open('NLTK-stop-word-list', 'r') as f2:
            mouse_file = f.read().split()  
            stopwords = f2.read().split()
            x = (' '.join(i for i in mouse_file if i.lower() not in (x.lower() for x in stopwords)))
            with open(output_location+'/'+new_file, 'w') as output_file: # Changed 'append' to 'write'
                output_file.write(x)

If you're in Python 3.7, you can do 
new_file = f"{file}_filtered.txt"

and 
with open(f"{output_location}/{new_file}", 'w') as output_file:
    output_file.write(x)

