Home > database >  FileNotFoundError: [Errno 2] No such file or directory: 'codedata.pkl'
FileNotFoundError: [Errno 2] No such file or directory: 'codedata.pkl'

Time:11-19

This is a school program to learn how to use file and directory in Python. So to do my best I create a function to open, set it as a variable and close properly my file.

But I got the error of the title:

FileNotFoundError: [Errno 2] No such file or directory: 'codedata.pkl'

def load_db():
""" load data base properly 
And get ready for later use

Return:
-------
    cd : (list) list of tuples
"""

file = open('codedata.pkl', 'rb')
codedata = pickle.loads(file)
file.close()

return codedata

From the interpreter, this is the line

file = open('codedata.pkl', 'rb')

Which is the problem, but I don't see where is the source of the problem.

Can anyone help me?

CodePudding user response:

Can you check what is the location of the file?

If your file is located at /Users/abc/Desktop/, then the code to open the file on python would be as shown below

file = open('/Users/abc/Desktop/codedata.pkl', 'rb')
codedata = pickle.load(file)
file.close()

You can also check if the file exists at the desired path by doing something like this

import os
filepath = '/Users/abc/Desktop/codedata.pkl'
if os.path.exists(filepath):
    file = open('/Users/abc/Desktop/codedata.pkl', 'rb')
    codedata = pickle.load(file)
    file.close()
else:
    print("File not present at desired location")
  • Related