尝试在Python中的文件夹中保存文件时出错?

时间:2017-01-09 15:06:45

标签: python python-2.7

文件夹结构

Project_Folder -|
                 Scripts-|
                          images -|
                          file.py

内部file.py

import requests
import os
import sys
sys.path.append('.')
url = "http://d2np4vr8r37sds.cloudfront.net/800313-kkenlukmjy-1481094947.jpg"
image = requests.get(url)
IMG_DIR = 'images'
IMG_DIR_ABS = os.path.join('.', IMG_DIR)
filename = "800313-kkenlukmjy-1481094947.jpg"
fullfilename = os.path.join(IMG_DIR_ABS, filename)
with open(fullfilename, 'wb') as f:
    f.write(image.content)
    f.close()

当我运行此代码时,我收到以下错误

python scripts/file.py
Traceback (most recent call last):
  File "scripts/file.py", line 9, in <module>
    with open(fullfilename, 'wb') as f:
IOError: [Errno 2] No such file or directory: './images/800313-kkenlukmjy-1481094947.jpg'

2 个答案:

答案 0 :(得分:2)

IMG_DIR_ABS = os.path.join('.', IMG_DIR)无法解析当前脚本的位置。 .是当前目录,而不是当前脚本的目录。

您想要做的是:

IMG_DIR_ABS = os.path.join(os.path.dirname(__file__), IMG_DIR)

__file__是当前正在运行的脚本的完整文件路径,它符合您对目录树的期望。

此方法的优点是您可以从任何目录启动脚本。

除此之外:f.close()块内无需withwith上下文在退出块时为您处理。

答案 1 :(得分:0)

您正在从Project_Folder运行脚本,但如果从该目录查看,则没有此类路径'./images/800313-kkenlukmjy-1481094947.jpg'。请尝试使用'./scripts/images/800313-kkenlukmjy-1481094947.jpg'