有没有一种方法可以在for循环python

时间:2020-02-17 22:30:47

标签: python class object

我有一个名为MediaFiles的类,并且我从用户那里获取路径,从中可以获取完整路径,文件名和文件扩展名,我想做的就是存储这些

2 个答案:

答案 0 :(得分:0)

听起来您应该使用MediaFile对象的列表。首先,您需要创建列表:

media_files = []

然后将元素添加到for循环的列表中:

media_files.append(MediaFile(name, filepath, extention))

答案 1 :(得分:0)

您可以创建一个列表,然后将对象存储在其中:

下面是代码:

#Define class in file named MediaFile.py
class MediaFile:

def __init__(self, file_name, file_path, file_type, file_comment=None, categorys=None, playlists=None):
        self.file_name = file_name
        self.file_path = file_path
        self.file_type = file_type
        self.file_comment = file_comment
        self.categorys = categorys
        self.playlists = playlists
    # New file which contains actual code:
    from MediaFile import MediaFile
    import os.path

    filenames = []
    filepaths = []
    fileextentions = []
    # empty list to store objects
    media_list=[]

    d = input('Enter a path to organise: ')
    for path in os.listdir(d):
        full_path = os.path.join(d, path)
        i=0
        if os.path.isfile(full_path):
            filepath = full_path
            name = os.path.splitext(os.path.basename(full_path))[0]
            extention = os.path.splitext(full_path)[1]
            i+=1
            # append the objects to a list
            media_list.append(MediaFile(name, filepath, extention))