gpt4 book ai didi

Python 找不到同一目录中的文件

转载 作者:行者123 更新时间:2023-11-28 20:45:57 25 4
gpt4 key购买 nike

我正在编写一个将文件附加到邮件的简单脚本,但找不到该文件。这是我的一个街区:

    # 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)

文件 20140210204804.kml 与脚本位于同一文件夹中。我遇到以下错误:

 IOError: [Errno 2] No such file or directory: '20140210204804.kml'

感谢任何帮助。

最佳答案

工作目录不是设置为脚本的目录,而是你启动脚本的当前目录。

使用 __file__ 确定文件位置,并将其用作使 filename 成为绝对路径的起点:

import os

here = os.path.dirname(os.path.abspath(__file__))

filename = os.path.join(here, '20140210204804.kml')

关于Python 找不到同一目录中的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21957131/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com