Python IOError: [Errno 13] Permission denied

With the code below, I get an IOError: [Errno 13] Permission denied , and I know that this is because the output directory is a subfolder 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 modified files to a subfolder of the input directory. How can I do this without receiving the "Allow Denial" error? Can the tempfile module be useful in this scenario?

+4
source share
2 answers

os.listdir will return the directory as well as file names. output is within inputdir , so with tries to open the directory for reading / writing.

What exactly are you trying to do? path, dirs, files not even used in recursive os.walk .

Edit: I think you are looking for something like this:

 import os INPUTDIR= "c:\\temp2\\CSV" OUTPUTDIR = "c:\\temp2\\CSV\\output" keyword = "KEYWORD" def make_path(p): '''Makes sure directory components of p exist.''' try: os.makedirs(p) except OSError: pass def dest_path(p): '''Determines relative path of p to INPUTDIR, and generates a matching path on OUTPUTDIR. ''' path = os.path.relpath(p,INPUTDIR) return os.path.join(OUTPUTDIR,path) make_path(OUTPUTDIR) for path, dirs, files in os.walk(INPUTDIR): for d in dirs: dir_path = os.path.join(path,d) # Handle case of OUTPUTDIR inside INPUTDIR if dir_path == OUTPUTDIR: dirs.remove(d) continue make_path(dest_path(dir_path)) for f in files: file_path = os.path.join(path, f) out_path = dest_path(file_path) with open(file_path, "r") as fh, open(out_path, "w") as fo: for line in fh: if keyword not in line: fo.write(line) 
+1
source

If you manage to write to the output directory outside the input movement directory, first write it there using the same code as above, and then move it to a subdirectory in the input directory. You can use os.move for this.

+1
source

Source: https://habr.com/ru/post/1403798/


All Articles