Question: ```
import os ,fnmatch
import os.path
import os

file_dir= '/home/deeghayu/Desktop/mec_sim/up_folder'
file_type = ['*.py']

for root, dirs,files in os.walk( file_dir ):
            for extension in ( tuple(file_type) ):
                for filename in fnmatch.filter(files, extension):
                    filepath = os.path.join(root, filename)
                    if os.path.isfile( filepath ):
                        print(filename , 'executing...');

                        exec(open('/home/deeghayu/Desktop/mec_sim/up_folder/{}'.format(filename)).read())

                    else:
                        print('Execution failure!!!')

```

Hello everyone I am working on this code which execute a python file using a python code. I need to save my output of the code as a text file. Here I have shown my code. Can any one give me a solution how do I save my output into a text file?

Answer: 
Piggybacking off of the original answer since they are close but it isn't a best practice to open and close files that way.

It's better to use a context manager instead of saying `f = open()` since the context manager will handle closing the resource for you regardless of whether your code succeeds or not.

You use it like,

```py

with open("file.txt","w+") as f:
    for i in range(10):
        f.write("This is line %d\r\n" % (i+1))

```
try

Open file

```
f= open("file.txt","w+")

```

Insert data into file

```
for i in range(10):
     f.write("This is line %d\r\n" % (i+1))

```

Close the file

```
f.close()

```