Downloading files from internet is so easy with Python. In this tutorial, we are going to learn how to download a file from internet and save it inside our device using Python’s built-in module. Both video and text tutorial are being provided for your better understanding.
Step 1: Import the urllib.request module into your program. This module has functions and classes which help us to open HTTP URLs from the internet. Next, create a variable named as file_url which will store the file’s URL that we want to download from internet. Here, r helps to prevent escaping the backslashes into the URL.
Step 2: Create a function named as download_file_information() and inside the function put a parameter named as url which will be the URL of the file that we want to download.
Step 3: Now, we will open the URL by using request.urlopen(url) function and store it inside a variable called fileOpen. After that, read the URL by using read() function and store the information inside file_info variable.
fileOpen = request.urlopen(url)
file_info = fileOpen.read()
Step 4: Now, convert the information inside file_info into string using str() function. Currently, the file’s information is in a single line formation. Split the information into lines using split() function and store the splitted lines into file_lines.
file_info_str = str(file_info)
file_lines = file_info_str.split('\\n')
Step 5: For storing the information that we found from the File URL, we will now create a new file named file.txt using open() function. Into the function, the first parameter takes the file name and the second parameter takes the Access Type. For our new file, we need the write access, so we will give w as the second parameter value. Now, we will write all the stored information of file_lines inside our new created file using a for loop using write() file function of Python.
newfile = open('file.txt',"w")
for info in file_lines:
newfile.write(info + '\n')
Step 6: Finally, close the created new file using close() function and call the download_file_information() function into a new line. Into the parameter of this function, we will put the URL file_url that we took earlier in the beginning of this program. After successfully calling the function, now you will see a new file named file.txt has been created into the same directory of your program file inside which you will get all the information of the file that we took from the internet.