Ok, today an easy task: get an image from the net and save it!
For the record, this image here:
Here is the code:
from urllib.request import urlopen
site = urlopen('http://placekitten.com/250/350')
data = site.read()
kitten = open('kitten.jpg','wb')
kitten.write(data)
kitten.close()
Just six lines of code and you're done. Here is the code in Sublime Text 3:
At the end in the folder where you have placed the file (.py) with this code (after you run it, of course) you will see this cute little kitten:
Let's look at the code for some details:
We import this method from the module urllib.request (this code is for python 3, for python 2 the library has another name).
Here we take the data from the site... where the pic is.
Here we create a file for writing data in it ("w" is for write, if we put "r" or nothing it would just open an existing file).
After we created the file, we write the data (the variable in wich we store the site.read() result, i.e.: the cat image).
After that we closed the data.
Note that when we use the with open(.....) as f: code we don't need to close the file, but this was not the case.
For the record, this image here:
Here is the code:
from urllib.request import urlopen
site = urlopen('http://placekitten.com/250/350')
data = site.read()
kitten = open('kitten.jpg','wb')
kitten.write(data)
kitten.close()
Just six lines of code and you're done. Here is the code in Sublime Text 3:
At the end in the folder where you have placed the file (.py) with this code (after you run it, of course) you will see this cute little kitten:
Let's look at the code for some details:
We import this method from the module urllib.request (this code is for python 3, for python 2 the library has another name).
Here we take the data from the site... where the pic is.
Here we create a file for writing data in it ("w" is for write, if we put "r" or nothing it would just open an existing file).
After we created the file, we write the data (the variable in wich we store the site.read() result, i.e.: the cat image).
After that we closed the data.
Note that when we use the with open(.....) as f: code we don't need to close the file, but this was not the case.
Comments
Post a Comment