Python - Delete all files EXCEPT for

后端 未结 2 414
予麋鹿
予麋鹿 2021-01-14 07:15

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         


        
相关标签:
2条回答
  • 2021-01-14 07:46

    An alternate way would be get the list of files (glob.glob returns a list) and then remove the one item you want to preserve.

    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):
       # get list of files that match
       cleanupFiles = glob.glob("c:\python\AIO*.*")
       cleanupFiles.remove(file_path)
       for cleanupFile in cleanupFiles:
          os.remove(cleanupFile)
    
    0 讨论(0)
  • 2021-01-14 07:55

    Try this instead

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

    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

    0 讨论(0)
提交回复
热议问题