连接到urllib文件

2024-10-01 02:22:12 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我尝试将扩展名.jpg连接到文件名,我会遇到一个问题,即“FileNotFoundError:[Errno 2]没有这样的文件或目录:”但是如果没有扩展名,保存很好

url = "http://" + str(self.get_image())
self.path_root = Path(__file__).resolve().parents[1] 
self.img_dir = str(self.path_root) + '\\static\\images\\newspapers\\' 

#This line throws a file not found error when I add the _ and .jpg 
self.fullfilename = '_'+ str(slugify(self.subheadline)) + '.jpg'

它以前工作过,但我把这个错误缩小到添加扩展名self.fullfilename是一个字符串

#This line saves fine but I need the extension as it's an image
self.fullfilename = str(slugify(self.subheadline)) 


urllib.request.urlretrieve(url, self.img_dir + '_'+ self.fullfilename)

这是stacktrace

 File "newspapers.py", line 271, in <module>
dw.save_image()
File "newspapers.py", line 149, in save_image
urllib.request.urlretrieve(url, self.img_dir + self.fullfilename)
File "C:\Users\peter\Anaconda3\lib\urllib\request.py", line 257, in urlretrieve
tfp = open(filename, 'wb')
FileNotFoundError: [Errno 2] No such file or directory: 
'E:\\mydirectory\\images\\newspapers\\_pere-aragones- 
vicepresident-de-la-generalitat-defiende-que-la-politica-desplace-a-la-represion'

Tags: imageselfurlimgrequestdirlineurllib
1条回答
网友
1楼 · 发布于 2024-10-01 02:22:12

我找到了答案,我认为这是因为您无法在urllib.request.urlretrieve中连接,即使它以前连接过

解决方案:

path 1 → self.img_dir = str(self.path_root) + '\\static\\images\\newspapers\\'
filename →  self.fullfilename = '_'+ str(slugify(self.subheadline)) + '.jpg'

self.sav_file_name = self.img_dir + self.fullfilename 

urllib.request.urlretrieve(url, self.sav_file_name)

相关问题 更多 >