【发布时间】:2018-10-22 19:42:55
【问题描述】:
我有一个目录,其中包含 ~2200 个文本文件。我需要删除任何不包含我定义的特定单词的文本文件。有人可以看看这段代码并就如何让它工作提出建议吗?现在,当我运行它时,它说找不到目录“C”。
另外,我想确保该目录中的每个文件都运行它。我需要包含下一个功能吗?
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)
另外,这里是完整的回溯:
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'
【问题讨论】:
-
您要删除那些inside文档或文档name中没有文本的那些?
-
对于您的路径问题 - 检查此答案:stackoverflow.com/a/2953843/366965
-
我想删除所有没有指定文本的 .txt 文件,不管文件名是什么。
-
@JoeNiland,这不是问题,可以,但在这种情况下不是
-
你能发一个完整的tracebak请求吗