Python-删除除以下文件以外的所有文件 [英] Python - Delete all files EXCEPT for

查看:341
本文介绍了Python-删除除以下文件以外的所有文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Python脚本,我正在尝试删除此目录中.csv文件以外的所有文件.在此行的"not"上获取语法错误:

I have a Python script and I'm trying to delete all files in this directory EXCEPT for the .csv file. Getting syntax error on the "not" in this line:

for CleanUp not in glob.glob("c:\python\AIO*.*"):

如果我删除"not",它将删除AIO.csv文件,但是我需要保留该文件,并且仅保留该文件.不清楚为什么它不起作用.

If I remove the "not", it will delete the AIO.csv file, but I need to preserve that file and ONLY that file. Not clear why it's not working.

import os
import glob
import time

file_path = "c:\python\AIO.csv"
while not os.path.exists(file_path):
    time.sleep(10)

if os.path.isfile(file_path):
 #Verifies CSV file was created, then deletes unneeded files.
    for CleanUp not in glob.glob("c:\python\AIO*.*"):
        os.remove(CleanUp)

推荐答案

尝试尝试

import os
import glob
import time

file_path = "c:\python\AIO.csv"
while not os.path.exists(file_path):
time.sleep(10)

if os.path.isfile(file_path):
    #Verifies CSV file was created, then deletes unneeded files.
    for CleanUp in glob.glob('C:/python/*.*'):
        print CleanUp
        if not CleanUp.endswith('AIO.csv'):    
            os.remove(CleanUp)

Glob不打印任何目录,仅打印文件,它还可以获取完整路径,因此您只需调用os.remove(CleanUp).这应该工作.它可以在我的Windows 7 x64机器上运行.

Glob doesn't print any directories, only files, and it also gets the entire path so you can just call os.remove(CleanUp). This should work. It works on my machine which is also Windows 7 x64.

我认为您的问题是您在路径c:\python\AIO*.*上循环,该路径是一个文件,因此它只执行一个循环并终止,从而跳过目录中的所有其他文件

I think your problem was that you where looping over the path c:\python\AIO*.* which is a file so it only does one loop and terminates which skips all other files in the directory

这篇关于Python-删除除以下文件以外的所有文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆