0

I want to remove the folders containing 'Done' in the folder name. Here is my code

import os
mainPath = os.getcwd() + "/MyFolder/"
folderList = os.listdir(mainPath)
tempList = folderList     # so that I can iterate while using remove()
print len(tempList)
print len(folderList)
for folder in tempList:
    if 'Done' in folder:
        folderList.remove(folder)
print len(tempList)       # expected: Not to change
print len(folderList)

The output I get is:
26
26
22
22

I do not understand why it is deleting items from testList. Shouldn't it delete only from folderList?

DSM
  • 342,061
  • 65
  • 592
  • 494
zud
  • 105
  • 2

1 Answers1

3

You're making the lists point to the same thing. use copy.deepcopy

Essentially when you do tempList = folderList it makes the two lists point to the same thing. If you want two copies of the same list that you can operate on separately you need to do:

import copy

tempList = copy.deepcopy(folderList)

If you know that all the items in your list are immutable, you can do tempList = folderList[:], but deepcopy is safer.

There's a wealth of information on this related question

Community
  • 1
  • 1
Adam Smith
  • 52,157
  • 12
  • 73
  • 112