如何从URL&中提取文件名附加一个词吗? [英] How to extract a filename from a URL & append a word to it?

查看:52
本文介绍了如何从URL&中提取文件名附加一个词吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下网址:

url = http://photographs.500px.com/kyle/09-09-201315-47-571378756077.jpg

我想在以下URL中提取文件名:09-09-201315-47-571378756077.jpg

I would like to extract the file name in this url: 09-09-201315-47-571378756077.jpg

获得此文件名后,我将使用该名称将其保存到桌面.

Once I get this file name, I'm going to save it with this name to the Desktop.

filename = **extracted file name from the url**     
download_photo = urllib.urlretrieve(url, "/home/ubuntu/Desktop/%s.jpg" % (filename))

在此之后,我将调整照片的大小,一旦完成,我将保存调整后的版本并将"_small"一词附加到文件名的末尾.

After this, I'm going to resize the photo, once that is done, I've going to save the resized version and append the word "_small" to the end of the filename.

downloadedphoto = Image.open("/home/ubuntu/Desktop/%s.jpg" % (filename))               
resize_downloadedphoto = downloadedphoto.resize.((300, 300), Image.ANTIALIAS)
resize_downloadedphoto.save("/home/ubuntu/Desktop/%s.jpg" % (filename + _small))

由此,我想要实现的是获取两个文件,一个是原始名称的原始照片,另一个是修改后名称的调整后大小的照片.像这样:

From this, what I am trying to achieve is to get two files, the original photo with the original name, then the resized photo with the modified name. Like so:

09-09-201315-47-571378756077.jpg

09-09-201315-47-571378756077.jpg

09-09-201315-47-571378756077_small.jpg

09-09-201315-47-571378756077_small.jpg

我该怎么做?

推荐答案

您可以使用 urllib.parse.urlparse

You can use urllib.parse.urlparse with os.path.basename:

import os
from urllib.parse import urlparse

url = "http://photographs.500px.com/kyle/09-09-201315-47-571378756077.jpg"
a = urlparse(url)
print(a.path)                    # Output: /kyle/09-09-201315-47-571378756077.jpg
print(os.path.basename(a.path))  # Output: 09-09-201315-47-571378756077.jpg

这篇关于如何从URL&中提取文件名附加一个词吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆