user3419487
user3419487

Reputation: 185

Saving Variable and retrieving later

I am trying to save the variable in python which will create a text file. Am i going wrong? I want to know where the file would be created/ Here is the code:

import pickle as pk
f = open("featuresvmt.txt", "w")
pk.dump(feature_svmt, f)
pk.dump(out_val, f)
f.close()

Upvotes: 1

Views: 980

Answers (2)

Döme
Döme

Reputation: 833

Your code can run and create a file where you run iPython. (Of course you must initialized both of used variable)
If you run iPython from terminal or command prompt, which directory is your actual path will contain the new file.

Upvotes: 0

unutbu
unutbu

Reputation: 879591

  • The file should be opened in binary writing mode: f = open("featuresvmt.txt", "wb").

  • The file featuresvmt.txt will be created in the current working directory. You can find the current working directory using os.getcwd(). Or, simply supply an absolute path: f = open("/path/to/featuresvmt.txt", "wb").


import pickle as pk
feature_svmt, out_val = 'foo', 12.34

with open("featuresvmt.txt", "wb") as f:
    pk.dump(feature_svmt, f)
    pk.dump(out_val, f)

with open("featuresvmt.txt", "rb") as f:
    print(pk.load(f))
    # foo
    print(pk.load(f))
    # 12.34

Upvotes: 4

Related Questions