我可以使用自己制作的代码找到文件,但是无法取消链接文件,因为出现错误提示找不到文件(“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')

最佳答案

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

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))

奖励: os.walkknown to be slow。替代方法os.scandir可以是20x faster under Windows。所以你也可以这样写:
# I think '.rxt' is a typo for '.txt'
def recursive_unlink(dirname):

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

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

recursive_unlink('h:')

关于python - 我无法在很长的文本中找到一个短语并将其取消链接,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/55608789/

10-15 02:03