I am trying to write some code that searches a group of files for a string and then places any files that include the string into a different directory which at the start of the program will not exist.
import os
import re
def test():
os.chdir("C:/Users/David/Files/TestFiles")
files = os.listdir(".")
os.mkdir("C:/Users/David/Files/TestFiles2")
for x in (files):
inputFile = open((x), "r")
content = inputFile.read()
inputFile.close()
if "Hello Word" in content:
with open ("C:/Users/David/Files/TestFiles2", "w") as outputFile:
outputFile.write(content)
When it runs I get the following error message
PermissionError: [Errno 13] Permission denied: 'C:/Users/David/Files/TestFiles2'
Just wondering if anyone can tell me why this error message appears.
You cannot open a directory for writing:
followed by
won’t work. Did you mean to add a filename to the latter statement?
If that was to be based on the
xfilename, you should add that name to the path:To move the file, use
shutil.move()instead; no need to ‘open’ the directory for that:Complete code, simplified: