Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python not finding file in the same directory

Tags:

python

I am writing a simple script that attaches file to a mail, but it is not finding the file. This is my one block:

    # KML attachment
    filename='20140210204804.kml'
    fp = open(filename, "rb")
    att = email.mime.application.MIMEApplication(fp.read(),_subtype="kml")
    fp.close()
    att.add_header('Content-Disposition','attachment',filename=filename)
    msg.attach(att)

The file 20140210204804.kml is present in the same folder as the script. I am getting below error:

 IOError: [Errno 2] No such file or directory: '20140210204804.kml'

Any help is appreciated.

like image 617
Abhishek dot py Avatar asked Feb 22 '14 16:02

Abhishek dot py


People also ask

Why Python Cannot find my file?

The Python FileNotFoundError: [Errno 2] No such file or directory error is often raised by the os library. This error tells you that you are trying to access a file or folder that does not exist. To fix this error, check that you are referring to the right file or folder in your program.

How do you reference a file in the same directory in Python?

The best and most reliable way to open a file that's in the same directory as the currently running Python script is to use sys. path[0]. It gives the path of the currently executing script. You can use it to join the path to your file using the relative path and then open that file.

How do I open files in the same folder?

You may the use the following to open up files in the same folder: f = open(os. path. join(__location__, 'bundled-resource.


1 Answers

The working directory is not set to the directory of the script, but to the current directory where you started the script.

Use __file__ to determine the file location and use that as a starting point to make filename an absolute path:

import os

here = os.path.dirname(os.path.abspath(__file__))

filename = os.path.join(here, '20140210204804.kml')
like image 73
Martijn Pieters Avatar answered Nov 14 '22 21:11

Martijn Pieters