Open Every File/subfolder In Directory And Print Results To .txt File
Solution 1:
For walking in subdirectories, there are two options:
Use
**
with glob and the argumentrecursive=True
(glob.glob('**/*.html')
). This only works in Python 3.5+. I would also recommend usingglob.iglob
instead ofglob.glob
if the directory tree is large.Use
os.walk
and check the filenames (whether they end in".html"
) manually or withfnmatch.filter
.
Regarding the printing into a file, there are again several ways:
Just execute the script and redirect stdout, i.e.
python3 myscript.py >myfile.txt
Replace calls to
print
with a call to the.write()
method of a file object in write mode`.Keep using print, but give it the argument
file=myfile
wheremyfile
is again a writable file object.
edit: Maybe the most unobstrusive method would be the following. First, include this somewhere:
import contextlib
@contextlib.contextmanagerdefstdout2file(fname):
import sys
f = open(fname, 'w')
sys.stdout = f
yield
sys.stdout = sys.__stdout__
f.close()
And then, infront of the line in which you loop over the files, add this line (and appropriately indent):
withstdout2file("output.txt"):
Post a Comment for "Open Every File/subfolder In Directory And Print Results To .txt File"