How to print to file in python

466 Views Asked by At

I am trying to get the output into a file rather than printing to the console using python, but so far the only thing that works is typing the following into the console python myPythonFile.py > outputTest.txt Here is the code I have:

import os

srcPath = ('path/to/my/files')
for folder, dirs, files in os.walk(srcPath):
    for file in files:
            fullpath = os.path.join(folder, file)
            with open(fullpath, 'r') as f:
                for line in f:
                    if "something" or "something else" or not "missingSomething" in line:
                        print(fullpath)
                        break 
1

There are 1 best solutions below

2
jsbueno On

just pass the file= keyword argument to print itself: print(fullpath, file=myfile)

(where myfile is an open file where you want your output to go, open it for writing (myfile = open("output.txt", "wt")) before your os.walk loops, of course)