I am writing a program which contains a function that checks if a number is prime— if it is, it adds it to a specific list, then uses the pickle module to save it as a file. When the function is called again, it opens the list (using pickle), then checks if the number is in the list. If it is, it is a prime, if not, it checks if it is a prime using a pretty basic technique.
Here is my code:
'''
List of functions:
_isPrime(n)_ : checks if n is a prime number
_remove(n)_ : removes n from the running list of primes and updates the pkl file
_prevPrimes(n)_ : generates a list of primes up to n
_view()_ : imports and prints pList
_delete()_ : deletes all of pList
'''
def isPrime(n):
import pickle
from math import sqrt
pList = pickle.load(open('primes.pkl', 'rb'))
x=2
if (type(n) != int) and (type(n) != long):
print "N is not an integer."
return False
if n in pList:
print "%d is a prime number." % (n)
return True
else:
while (sqrt(n) >= x):
if ((n%x) != 0):
x = x + 1
if (sqrt(n) < x):
pList.append(n)
pList = sorted(pList)
pickle.dump(pList, open('primes.pkl', 'wb'))
print "%d is a prime number." % (n)
return True
if ((n%x)==0):
print "%d is not a prime number." % (n)
return False
pList = sorted(pList)
pickle.dump(pList, open('primes.pkl', 'wb'))
# NEW FUNCTION
def prevPrimes(n):
from time import clock
startTime= clock()
import pickle
from math import sqrt
pList = pickle.load(open('primes.pkl', 'rb'))
z = abs((max(pList)) - n)
y= max(pList)
if (z==0):
print "Done"
while (y <= n):
pList = pickle.load(open('primes.pkl', 'rb'))
if isPrime(y):
if y not in pList:
pList.append(y)
y= y + 1
pList = sorted(pList)
pickle.dump(pList, open('primes.pkl', 'wb'))
print startTime
# NEW FUNCTION
def remove(n):
import pickle
pList = pickle.load(open('primes.pkl', 'rb'))
view()
pList.remove(n)
pickle.dump(pList, open('primes.pkl', 'wb'))
view()
# NEW FUNCTION
def view():
import pickle
pList = pickle.load(open('primes.pkl', 'rb'))
print pList
# NEW FUNCTION
def delete():
import pickle
pList = [2, 3, 5]
pickle.dump(pList, open('primes.pkl', 'wb'))
view()
It works fine in the Python shell.
The error that occurs is if the function actually calls. I accomplished this by doing from primenum import isPrime. However, then it gets an error with the I/O (with pickle)… Here’s a picture:

As you can see, the primes.pkl file is clearly there.
How do I fix this? Thanks in advance for any suggestions 🙂
You already discovered how to import your function correctly:
from primenum import isPrime
or refer to the full name:
You need to use a full path to store your pickle file; otherwise python looks for it in the local directory only. Perhaps store it in your home directory:
then later open the file with: