John.E John.E - 4 months ago 11
Python Question

Define list objects

I have the following text file:


12345;XMEN;science finction;2010

85689;SUPERMAN;science finction;2015

87985;upside downcomics 2013

8547;saw;thriller;2000

12321;now you see me;horror;2012


I need to turn it into a list and then assign each object a name to work with, like: "code;movie name;movie genre;year of release"

So far it looks like this

dvds = open ("dvds.txt",'r')
dvdslist = [line.split(';') for line in dvds.readlines()]


Which gives:


[['12345', 'XMEN', 'science finction', '2010\n'], ['85689', 'SUPERMAN', 'science finction', '2015\n'], ['87985', 'upside downcomics\t2013\n'], ['8547', 'saw', 'thriller', '2000\n'], ['12321', 'now you see me', 'horror', '2012']]


How do i proceed next?Any help is much appreciated

Answer Source

"Turn it into a list and then assign each object a name to work with". Without further details this sounds like what you described:

class create_dvd:
    def __init__(self, code, name, genre, year):
        self.code = code
        self.name = name
        self.genre = genre
        self.year = year


with open('dvds.txt', 'r') as f:
    fcontents = f.readlines()

# strip off newlines
fcontents = [c.strip() for c in fcontents]

# filter out empty entries
fcontents = filter(None, fcontents)

dvd_list = []

for item in fcontents:
    # create a dvd for each entry
    ad = create_dvd(*item.split(';'))
    # append result to a list
    dvd_list.append(ad)

Demo:

# get the first dvd object from list
dvd_1 = dvd_list[0]

# print contents of first dvd instance
print 'DVD #1: {c}, {n}, {g}, {y}\n'.format(c=dvd_1.code, n=dvd_1.name, g=dvd_1.genre, y=dvd_1.year)

# print all dvds
for i, dvd in enumerate(dvd_list):
    print 'DVD #{idx}: {c}, {n}, {g}, {y}'.format(idx=i+1, c=dvd.code, n=dvd.name, g=dvd.genre, y=dvd.year)

output:

DVD #1: 12345, XMEN, science finction, 2010

DVD #1: 12345, XMEN, science finction, 2010
DVD #2: 85689, SUPERMAN, science finction, 2015
DVD #3: 87985, upside down, comics, 2013
DVD #4: 8547, saw, thriller, 2000
DVD #5: 12321, now you see me, horror, 2012