8

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.

1
  • 2
    How are you running the script? The current directory isn't necessarily the same as the script's location. Commented Feb 22, 2014 at 16:40

1 Answer 1

27

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')
Sign up to request clarification or add additional context in comments.

3 Comments

Excellent !! I didn't think this way. I can understand what "_file_" did, but is there any link that can explain why/how it did?
@Abhishekdotpy: most of the 'trick' here is using the os.path module; look for abspath and dirname there. __file__ is just the filename of the current module, which can be relative to the working directory.
@Abhishekdotpy: __file__ is documented both in the import statement documentation and the Python datamodel document.

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.