With the below code I receive IOError: [Errno 13] Permission denied, and I know this is due to the output directory being a sub-folder of the input directory:
import datetime
import os
inputdir = "C:\\temp2\\CSV\\"
outputdir = "C:\\temp2\\CSV\\output\\"
keyword = "KEYWORD"
for path, dirs, files in os.walk(os.path.abspath(inputdir)):
for f in os.listdir(inputdir):
file_path = os.path.join(inputdir, f)
out_file = os.path.join(outputdir, f)
with open(file_path, "r") as fh, open(out_file, "w") as fo:
for line in fh:
if keyword not in line:
fo.write(line)
However, when I change the output folder to: outputdir = "C:\\temp2\\output\\" the code runs successfully. I want to be able to write the modified files to a sub-folder of the input directory. How would I do this without getting the ‘Permission denied’ error? Would the tempfile module be useful in this scenario?
os.listdirwill return directory as well as file names.outputis withininputdirso thewithis trying to open a directory for reading/writing.What exactly are you trying to do?
path, dirs, filesaren’t even being used in the recursiveos.walk.Edit: I think you’re looking for something like this: