我无法在很长的文本中找到一个短语并将其取消链接

时间:2019-04-10 09:09:45

标签: python

我可以使用此代码找到文件,但无法取消链接,因为出现错误提示找不到文件(“ my_filename.rxt”) 有人可以帮我吗?

import os
for foldername, subfolders, filenames in os.walk("h:"):
    for subfolder in subfolders:
        for filename in filenames:
            if filename.endswith(".rxt"):
                print(filename)
                os.unlink(filename)

thanks. I was able to do this program with this.

导入操作系统

def recursive_unlink(dirname):

for entry in os.scandir(dirname):
    if entry.is_dir():
        recursive_unlink(os.path.abspath(entry))

    elif entry.name.endswith('.rxt'):
        os.unlink(os.path.abspath(entry))

recursive_unlink('h:\ desktop')

但是当我尝试在文件中查找文本并删除其中包含某些文本的文件时,我无法。 有人可以再次帮助我吗?

import os

def recursive_unlink(dirname):

    for entry in os.scandir(dirname):
        if entry.is_dir():
            recursive_unlink(os.path.abspath(entry))

        elif entry.name.endswith('.rxt'):
            file = os.path.join(foldername,filename)
            file = open(file, 'r')
            phrase = findWholeWord('MZ・         ク       @                                      コ エ    ヘ!クLヘ!This program cannot be run in DOS mode.')(file)
            if phrase == True
                os.unlink(os.path.abspath(file))

recursive_unlink('h:\\desktop')

1 个答案:

答案 0 :(得分:3)

正如@AJS指出的那样,您的问题是您没有为文件提供absolute path,因此它找不到实际的文件。不幸的是,我认为他当前寻找绝对路径的答案是不正确的。这应该起作用:

open_restaurants = [restaurant.get("name") for restaurant in restaurants if not restaurant.get("is_closed")]

Output: ["Fork & Fig"]



奖金import os # actually I'm not sure if "h:" is a legal path for foldername, subfolders, filenames in os.walk("h:"): for filename in filenames: if filename.endswith('.txt'): os.unlink(os.path.join(foldername, filename)) known to be slow。替代方法os.walk可以是20x faster under Windows。所以你也可以这样写:

os.scandir