4

I try to use www.pythonanywhere.com to build the web application, now I have create a directory as "/ > home > myid_xxx > mysite > FM", and under the 'FM' directory, there are two files : demo1.py and demo_pickle_file.pkl .

I try to cPickle.load(open('demo_pickle_file.pkl','rb')) in 'demo1.py', but the pythonanywhere console shows :

IOError: [Errno 2] No such file or directory: 'demo_pickle_file.pkl'

So, how to correctly access the pickle file ?

3
  • make sure your running path is inside of the directory with demo_pickle_file.pkl, otherwise you need the entire or relative path. Commented Dec 15, 2013 at 3:56
  • As I am a newbie of pythonanywhere, I didn't catch your meaning . Does "make sure your running path is inside of the directory with demo_pickle_file.pkl" mean to put the "demo1.py" and "demo_pickle_file.pkl" in the same folder ? If so, I already done that. If not, " otherwise you need the entire or relative path", how to do that ? Thanks .. Commented Dec 15, 2013 at 4:04
  • 1
    Consider printing out os.getcwd() to determine where python might be looking. Commented Dec 15, 2013 at 5:22

1 Answer 1

7

Since the pickle file is in the same directory asdemo1.pyyou could use something like the following to find the path to it from the path to the script:

import os
import cPickle as pickle

my_dir = os.path.dirname(__file__)
pickle_file_path = os.path.join(my_dir, 'demo_pickle_file.pkl')

with open(pickle_file_path, 'rb') as pickle_file:
    demo = pickle.load(pickle_file)
Sign up to request clarification or add additional context in comments.

4 Comments

You can, of course, print pickle_file_path to learn what the actual path is to the file.
i finally hardcode the pickle file's absolute path to solve the issue. I just want to know more about the mechanize to find the file in pythonanywhere.
I would suggest avoiding the hardcoding of paths into code -- either by using the technique shown in my answer or using some kind of configuration file (see the ConfigParser module). Of course you'll still need to determine the path to the configuration file itself, so even then the approach shown can come in handy.
yes, your code is more elegent. i will replace the hardcoded path with that. thanks again..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.