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.
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.
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.
You may the use the following to open up files in the same folder: f = open(os. path. join(__location__, 'bundled-resource.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With