0
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?

2 Answers 2

1

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,


with open("file.txt","w+") as f:
    for i in range(10):
        f.write("This is line %d\r\n" % (i+1))
Sign up to request clarification or add additional context in comments.

Comments

0

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()

2 Comments

this is not exactly answer i need. I need to save my output on the terminal into a txt file.
read your question once again.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.