0

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 Answers1

2

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)

jsbueno
  • 99,910
  • 10
  • 151
  • 209
  • I am using python 2.7, so it is giving me syntax error for `print(fullpath, file=myfile)` specifically for the "=" – Korey Hardy Apr 14 '22 at 15:09
  • "I am using python 2.7, ", so don't. Seriously, why? The thing can't even be downloaded from a standard location for years now. Upgrade to 3.10 and save yourself a lot of work (this sort of file handling can use the new "pathlib" for example) That said, just add "`from __future__ import print_function`" to the top of your file. – jsbueno Apr 14 '22 at 15:12