user1836292
user1836292

Reputation: 99

Pickle isn't working and hence txt file created is empty

Write a program that defines a class Movie that has the following attributes: title, director, length (length of the movie in minutes). Create five objects of class Movie, pickle them, and store them in a file.

#!/usr/local/bin/python
import pickle
class Movies:
    def __init__(self,title,director,length):
        self.x=title
        self.y=director
        self.z=length

def main():
    movie1 = Movies(1,100,10)
    movie2 = Movies(2,200,20)
    movie3 = Movies(3,300,30)
    movie4 = Movies(4,400,40)
    movie5 = Movies(5,500,50)

main()

import pickle
try:
    file=open("movies.txt","w")
    fold =[movie1,movie2,movie3,movie4,movie5]
    pickle.dump[fold,file]

except IOError:
    print("file could not be open")
except ValueError:
    print("could not make list")
except:
    print("some unknown error")
else:
    print("successfully done!")
finally:
    print("printing always")
    file.close()

So everything works fine but the movies.txt file is empty. Im new to Python so I have less experience with exception handling. But from what I understood pickle isnt working.

Upvotes: 1

Views: 714

Answers (1)

Emil L
Emil L

Reputation: 21081

You are defining the movie variables in the function main however they will not be present in the scope where you define your try block. Additionally, as have been noted in the comments of the question you are using the wrong syntax to call pickle.dump. It should use parentheses and not squeare brackets, i.e. pickle.dump(fold,file).

Finally moving your try block into the main function will make things work as expected. Like this:

def main():
    movie1 = Movies(1,100,10)
    movie2 = Movies(2,200,20)
    movie3 = Movies(3,300,30)
    movie4 = Movies(4,400,40)
    movie5 = Movies(5,500,50)

    import pickle
    try:
        file=open("movies.txt","w")
        fold =[movie1,movie2,movie3,movie4,movie5]
        pickle.dump(fold,file)

    except IOError:
        print("file could not be open")
    except ValueError:
        print("could not make list")
    except:
        print("some unknown error")
    else:
        print("successfully done!")
    finally:
        print("printing always")
        file.close()

main()

There are still a bunch of style issues with the code, but this should get you going!

Upvotes: 1

Related Questions