Check of the list in the cycle



  • import os
    import win32api
    
    path = ['E:/keys.txt', 'G:/keys.txt']  # Эти файлы не существуют
    
    result_path = path
    for x in path:
        if os.path.isfile(x) is False:
            volume_lbl = win32api.GetVolumeInformation(x[:3])
            print(f'Ключ отсутствует на накопителе {x[:3]} с меткой {volume_lbl[0]}!')
            result_path.remove(x)
    

    The function shall verify that there is a file on the way on the list. Problem is, if the files don't exist, the cycle. for interrupted without reaching the end of the list path♪ After the result_path will contain ['G:/keys.txt'], although by my logic the list should remain empty.

    I tried to invert if, do the cycle while (a-l C++) it didn't work.
    How do you fix it?



  • It's all about memory management in the python.

    You create an object. list path

    Then you take it. result_path His meaning.

    Inside the python, it doesn't work the way most newcomers expect.

    result_path and path References to the same list

    As a result, when changed result_path change path♪ This leads to the work of your cycle for nothing you've ever thought about.

    What do we do? Use such designs as:

    result_path  = deepcopy(path)
    

    or

    result_path  = list(path)
    


Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2