Search code examples
pythonpython-3.xfileemail-attachments

How can I construct a Python3 file object from a full file path (string)


I am updating a mailer from Python2. There I used the line

attachFile.set_payload(file(attachment[1]).read())

How can I create the same effect in Python3? I tried

attachFile.set_payload(File(attachment[1]).read())

but am told that File() is not known. file() does not work either.

attachment[1] contains the full path to the file on the Ubuntu file system.

Thank you.


Solution

  • Try:

    attachFile.set_payload(open(attachment[1], "rb").read())
    

    which is opening file in binary mode (I assume this is what is needed here).