使用os.listdir(路径)时无法打开文件

时间:2017-11-10 16:42:41

标签: windows smtp python-3.6 mime

for file in os.listdir(path):
try:
    with open(file, 'r') as fp:
        msg = MIMEBase('application', "octet-stream")
        msg.set_payload(fp.read())
    encoders.encode_base64(msg)
    msg.add_header('Content-Disposition', 'attachment', filename=os.path.basename(file))
    outer.attach(msg)
except:
    print("Unable to open one of the attachments. Error: ", sys.exc_info()[0])
    raise

composed = outer.as_string()

我得到" FileNotFoundError:[Errno 2]没有这样的文件或目录"但文件存在!可能是os.listdir()对象类型?

1 个答案:

答案 0 :(得分:0)

os.listdir函数仅返回文件名。您应该连接路径和文件名:

for file in os.listdir(path):
    try:
        with open(ps.path.join(path, file), 'r') as fp:
    ...