I have a directory with ~2200 text files in them. I need to delete any text file that does not contain the specific words i've defined. Can someone please look at this code and make a suggestion on how to get it working? Right now, when i run this it says it can't find the directory "C".
Also, i want to make sure that this runs for every file within that directory. Do i need to include a next function?
import os
path = r'C:\Users\user\Desktop\AFL codes to test'
words = ['buy', 'sell']
for root, dirs, files in os.walk(path):
for file in path:
if not any(words in file for words in words):
os.remove(file)
Also, here is the full traceback:
runfile('C:/Users/user/.spyder-py3/DELETE FILES THAT DONT CONTAIN CERTAIN WORDS.py', wdir='C:/Users/user/.spyder-py3')
Traceback (most recent call last):
File "<ipython-input-23-dbc80e182b2b>", line 1, in <module>
runfile('C:/Users/user/.spyder-py3/DELETE FILES THAT DONT CONTAIN CERTAIN WORDS.py', wdir='C:/Users/user/.spyder-py3')
File "C:\Users\user\Anaconda31\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:\Users\user\Anaconda31\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/user/.spyder-py3/DELETE FILES THAT DONT CONTAIN CERTAIN WORDS.py", line 9, in <module>
os.remove(file)
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'C'
This is the error after trying shutil.rmtree
runfile('C:/Users/user/.spyder-py3/DELETE FILES THAT DONT CONTAIN CERTAIN WORDS.py', wdir='C:/Users/user/.spyder-py3')
Traceback (most recent call last):
File "<ipython-input-16-dbc80e182b2b>", line 1, in <module>
runfile('C:/Users/user/.spyder-py3/DELETE FILES THAT DONT CONTAIN CERTAIN WORDS.py', wdir='C:/Users/user/.spyder-py3')
File "C:\Users\user\Anaconda31\lib\site-packages\spyder\utils\site\sitecustomize.py", line 705, in runfile
execfile(filename, namespace)
File "C:\Users\user\Anaconda31\lib\site-packages\spyder\utils\site\sitecustomize.py", line 102, in execfile
exec(compile(f.read(), filename, 'exec'), namespace)
File "C:/Users/user/.spyder-py3/DELETE FILES THAT DONT CONTAIN CERTAIN WORDS.py", line 12, in <module>
shutil.rmtree(full_path)
File "C:\Users\user\Anaconda31\lib\shutil.py", line 494, in rmtree
return _rmtree_unsafe(path, onerror)
File "C:\Users\user\Anaconda31\lib\shutil.py", line 376, in _rmtree_unsafe
onerror(os.listdir, path, sys.exc_info())
File "C:\Users\user\Anaconda31\lib\shutil.py", line 374, in _rmtree_unsafe
names = os.listdir(path)
NotADirectoryError: [WinError 267] The directory name is invalid: 'C:/Users/user/Desktop/AFL codes to test/newfile1.txt'