Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

How to use open() func?

I wanted to save the list of items in shopping_list, so used open():

def save(shopping_list):
  save = open('items.txt', 'w')
  save.write(str(shopping_list))
  save.close
  1. For example as a user I want to continue working with my saved list, how can I extract data from the text file and add it to shopping_list.py?

  2. And when try to append or extend data from text file to a list it gives me 'None':

my_list = []
new = open('items.txt')

# 'items.txt' has "1, 2, a" as a string.

for item in new:
  print(my_list.append(item))

Thank's in advance.

2 Answers

So, first off, you don't want to actually save the list as a string. This is a shopping LIST. So it's best to just save the data as a list. Then when starting the program, read that list. This is data IO. You can use a module called Pickle. This module writes data to files and also reads data from files with the "load" command.

This way you dump("data") where data is a list. To a file. Than you load("data") which is a list into you program. This way it's already in list form and ready for you application to use as it expects to use it.

Here is the link, you will have to paste and cut I am in a hurry.

https://docs.python.org/2/library/pickle.html

FYI: If you read the module and try some steps and still have issues. Please let me know. It's a heavy topic and easier to answer specific questions about what you don't understand than to try and re-write the documentation. Be it docs can be tuff to understand. Let me know and when I get back later I can definitely try and make this more clear.

Thanks!

Thank you so much, Ryan, I haven't dived in pickle library deeply yet, but I got how to use it with shopping_list, here are functions, which I made for saving and loading data:

import pickle

def save_list(shopping_list):
  save = open('shopping_list_save.txt', 'wb')
  pickle.dump(shopping_list, save)
  save.close()

def load_saved(shopping_list):
  save = open('shopping_list_save.txt', 'rb')
  shopping_list = pickle.load(save)
  save.close()
  return shopping_list

Hey that's great news. Good work for looking into the pickle library. I just made the suggestion and you did the leg work for yourself. That's awesome. Good luck and happy pickling lol.

Try the Input and Output tutorial in the Python Docs, on reading and writing files.