user8837495
user8837495

Reputation: 51

How to print a list of file names using a method

I'm new to python, and i'm trying to create a class (with a method) that takes file names from a directory, appends them into a list, and then prints it out.

class data:
    def __init__(self):
        self.images = []

    def showImg(self):           
        path = r"C:\path"
        dirs = os.listdir(path)
        for file in dirs:
            self.images.append(file)
        return self.images

data1 = data()
print (data1.images)

When I try to run the code all I get is "[ ]" as output.

Upvotes: 0

Views: 42

Answers (1)

Kvothe
Kvothe

Reputation: 128

You forgot to call the function showImg? You have three options:

You can add it in your init

def __init__(self):
    self.images = []
    self.showImg()

or call it later and then you get it with the variable:

data1 = data()
data1.showImg()
print (data1.images)

or call it directly and get the return list from the function:

data1 = data()
print (data1.showImg())

Upvotes: 1

Related Questions