在Python中尝试将文件保存到文件夹时出错?
文件夹结构在Python中尝试将文件保存到文件夹时出错?,python,python-2.7,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-kkenlukmj
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'
python脚本/file.py
回溯(最近一次呼叫最后一次):
文件“scripts/File.py”,第9行,在
将open(fullfilename,'wb')作为f:
IOError:[Errno 2]没有这样的文件或目录:'./images/800313-kkenlukmjy-1481094947.jpg'
IMG\u DIR\u ABS=os.path.join('.',IMG\u DIR)
不解析当前脚本的位置
是当前目录,而不是当前脚本的目录
您要做的是:
IMG_DIR_ABS = os.path.join(os.path.dirname(__file__), IMG_DIR)
\uuuu file\uuuu
是当前运行脚本的完整文件路径,它符合给定目录树的预期
此方法的优点是可以从任何目录启动脚本
旁白:在
with
块中不需要f.close()
<带有上下文的code>在退出块时为您处理该问题。IMG_DIR_ABS=os.path.join('.',IMG_DIR)不会解析当前脚本的位置
是当前目录,而不是当前脚本的目录
您要做的是:
IMG_DIR_ABS = os.path.join(os.path.dirname(__file__), IMG_DIR)
\uuuu file\uuuu
是当前运行脚本的完整文件路径,它符合给定目录树的预期
此方法的优点是可以从任何目录启动脚本
旁白:在
with
块中不需要f.close()
<退出块时,使用上下文处理代码>。您正在从Project_文件夹运行脚本,但如果您从该目录查看,则没有这样的路径。/images/800313-kkenlukmjy-1481094947.jpg'
。尝试使用。/scripts/images/800313-kkenlukmjy-1481094947.jpg'
。您正在从Project\u文件夹运行脚本,但如果从该目录查看,则没有这样的路径。/images/800313-kkenlukmjy-1481094947.jpg'
。尝试改用。/scripts/images/800313-kkenlukmjy-1481094947.jpg'