0

I want to return a list based on a directory listing for sorting. My problem is that when I do a loop for each file in that list and attempt to remove based on the user inputted extension with .endswith() it doesnt seem to update the list correctly (but it does print out "removing file..."). Am I doing something wrong? should I be updating or returning the list (files) somewhere I am not?>

Also if I set the dirlist variable files as files=file_list.sort() it returns none, I have to set files=sorted(file_list) ... why is that?

import os

class Sort:

dirchoice = os.getcwd()
file_list = list(os.listdir(dirchoice))
files=sorted(file_list)

def file_extension(self):
    if input("Would you like to specify a particular file extension [Y/N]").lower() == ('y' or 'yes'):
        ext=input("filetype>")
        ext = str(ext)
        for file in self.files:
            print(file)
            if not file.endswith(ext):
                self.files.remove(file)
                print("removing " +file+ " from list...")
        return self.files
        print("File Contents:  ")        
        pprint.pprint(self.files)     
        return self.file_extension()
Sanjay Manohar
  • 6,920
  • 3
  • 35
  • 58
conma293
  • 45
  • 2
  • 9
  • 3
    Questions seeking debugging help (**"why isn't this code working?"**) must include the desired behavior, *a specific problem or error* and *the shortest code necessary* to reproduce it **in the question itself**. Questions without **a clear problem statement** are not useful to other readers. See: [How to create a Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – MattDMo Sep 04 '15 at 23:37
  • Have you considered using a debugger? Add breakpoints in your program and find out which line is causing the subject of your bug. – Poriferous Sep 05 '15 at 01:18
  • sorry guys, first post, is that better? I cant even make this work on IDLE, it must be something im missing with loops and lists from a dirlist – conma293 Sep 05 '15 at 01:31
  • ok I solved it - you cant remove on a list your iterating through already for some reason? so I removed 'file' from 'file_list' and then updated 'files' later.... why is this ? – conma293 Sep 05 '15 at 01:44

1 Answers1

1

Short answer to your last comment:

it's because the for loop retrieves items from the files list in sequence, at the start of each iteration of the loop. It uses a hidden integer index to do this. So if elements are removed during iteration, the index gets "out of sync".

This post contains some more detail: How to remove list elements in a for loop in Python?

Community
  • 1
  • 1
Sanjay Manohar
  • 6,920
  • 3
  • 35
  • 58
  • Thanks Sanjay, is there a similar reason why I couldn't use file_list.sort() but sorted(file_list) was ok? – conma293 Sep 05 '15 at 06:34