Trying to write a small script in Python to delete files, but the os.remove function is having issues with the file path. Note if I comment out os.remove("C:\\Users\The User\Downloads\test.txt") it runs fine and will print 'gone'. I don't understand why when assigning the path to the variable it works but os.remove doesn't like the same thing.
import os
import re
search ='test.txt'
path = "C:\\Users\The User\Downloads"
def find(search, path):
for root, dirs, files in os.walk(path):
if search in files:
return True
else:
return False
result = find(search, path)
if(result == False):
os.remove("C:\\Users\The User\Downloads\test.txt")
print('gone')
Here's the error message:
OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\Users\The User\Downloads\test.txt'
TrueorFalseinstead of'yes'and'no'.find()that indicates this is not the exact code you are running. Also, please fix your indentation, as it's not clear what you're code is actually doing. Once you've done that, tell us what issuesos.removeis having, and please include any errors in your question, in full.find()is not going to work generally because, at best, it will tell you ifsearchis a file somewhere underpath, not whether it's in the top-levelpathdirectory.