在Python中删除文件时出现文件路径问题

时间:2018-11-26 02:02:45

标签: python filepath delete-file

试图用Python编写一个小的脚本来删除文件,但是os.remove函数的文件路径有问题。请注意,如果我将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') 注释掉,它将运行正常并且将打印“ gone”。我不明白为什么在将路径分配给变量时起作用,但是os.remove不喜欢同一件事。

public class Valor {

public static double variavel;

public static void setVariavel(double newVariavel){
    variavel = newVariavel;
}

这是错误消息:

OSError:[WinError 123]文件名,目录名或卷标语法不正确:'C:\ Users \ User \ Downloads \ test.txt'

  
    
      

    
  

1 个答案:

答案 0 :(得分:2)

我认为您应该只返回要删除的文件的完整路径,如果路径不是None,则调用os.remove()。在您的代码中,检查search中是否存在files,但是files是一个列表,您需要遍历并获取匹配的文件以确定其当前目录。然后,您可以使用root获取完整路径,以后再使用该路径进行删除。

演示:

from os import environ
from os import walk
from os import remove
from os.path import join

def find(search, path):
    for root, _, files in walk(path):

        # Go through each file
        for file in files:

            # Check if the file matches the search
            if file == search:

                # return full path
                return join(root, file)

# Get path if any
result = find(search="test.txt", path=join(environ["USERPROFILE"], "Downloads"))

# Only delete file if not None
if result:
    remove(result)
    print('Deleted', result)

您还可以在此处使用next()来缩短find()

def find(search, path):
    for root, _, files in walk(path):
        return next((join(root, file) for file in files if file == search), None)

注意:您可以使用os.path.join(os.environ['USERPROFILE'], 'Downloads')而不是对C:\\Users\The User\Downloads进行硬编码。