【问题标题】:File can't be opened when using os.listdir(path)使用 os.listdir(path) 时无法打开文件
【发布时间】:2018-04-23 23:02:21
【问题描述】:
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] No such file or directory”,但文件存在!可能是 os.listdir() 对象类型?

【问题讨论】:

    标签: windows smtp python-3.6 mime


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2021-08-10
      • 1970-01-01
      • 1970-01-01
      • 2012-11-12
      • 2019-01-06
      • 2021-09-29
      • 2011-09-14
      • 2010-12-17
      • 2020-12-15
      相关资源
      最近更新 更多