pythonpython-osfile-manipulation

nested for loop giving no output when working with two lists


I am making a file sorter in Python and I have two lists. One is called downloads, which holds the names of all of my files in my downloads directory, and the other is called files, which is intended to hold all of the needed information about each file so that I can make user interaction more simple. I am trying to bring all of the information from downloads into the name value of each download_files object. Whenever I run the code, it does not output anything, and it does not give any sort of error message.

class download_files:
    def __init__(self, name, type):
        self.name = name
        self.age = type

import os

a = 0
b = 0
downloads = os.listdir(r"C:\Users\crazy\Downloads\\")
files = []

def main():
    for a in downloads:
        for b in files:
            b = download_files(a, 0)
            print()

main()

Solution

  • Instead of:

    a = 0  # unused value
    b = 0  # unused value
    downloads = os.listdir(r"C:\Users\crazy\Downloads\\")
    files = []
    
    def main():
        for a in downloads:
            for b in files:  # iteration over empty list
                b = download_files(a, 0)
                print()
    
    main()
    

    you want to do something more like:

    downloads = os.listdir(r"C:\Users\crazy\Downloads\\")
    files = [download_files(name, 0) for name in downloads]
    

    i.e. build files out of download_files objects built out of the elements of downloads, rather than creating an empty files and then trying to loop over it.

    Note: a better name for your download_files might be something like DownloadFile -- it's a single file (right?), and classes usually get CamelCase names in Python to distinguish them from instances and functions (which get snake_case names).