# 5 Quick Python Projects

## Introduction

In this blog, we'll be building five different Python projects. These projects will be a little bit above the beginner's level, so we can consider them as **Intermediate Python Projects**. So, we are going to build the below mentioned five projects :

1.  Web Scraping Program
2.  Renaming Bulk Files
3.  Getting Weather Information
4.  Password Generator
5.  QR Codes with Python

Having said that, let's jump to building these cool projects.

## Web Scraping Program

In this project, we'll be using Web Scraping to **get the image link of the profile image of a particular Github user**. So, what our program is going to do, it's going to ask for a Github username and then it will return the image link of that account.

![](https://res.cloudinary.com/dlomjljb6/image/upload/v1/media/blog/uploads/2021/05/29/screenshot-1%5Flxtcma)

Before we start we need to install two external Python libraries - **requests** and **bs4** :

```bash
pip install requests bs4
```

The above command will install these two libraries and now we are ready for coding.

So, the first thing we need to do is to import these ibraries in our code :

```python
import requests
from bs4 import BeautifulSoup as bs
```

Now, let's understand how we are going to proceed. First, we are going to fetch the user's profile on Github using requests and pass all the HTML content of the page to the BeautifulSoup to parse using an HTML parser. Now, we need to understand one thing. To fetch the user's image, we need to visit its profile and inspect the HTML content first in order to visualize how we are going to extract the image. SO, after inspecting, we have this HTML content that is used for the profile image (as of now):

```html
<img
  style="height:auto;"
  alt=""
  width="260"
  height="260"
  class="avatar avatar-user width-full border color-bg-primary"
  src="https://avatars.githubusercontent.com/u/47353498?v=4"
/>
```

In this HTML content, we need to find a unique attribute using which we can fetch the **src** of the **img** tag. We can use the class **avatar avatar-user**for this, and this way we can get the image link. Now let's jump to the code :

```python
def get_profile_image(username) -> str:
    url = f"https://github.com/{username}/"
    res = requests.get(url)
    soup = bs(res.content, 'html.parser')
    profile_image = soup.select('img.avatar.avatar-user')[0]['src']
    return profile_image
```

In the above code, we are first making a GET request on the user's profile and then using the select method in soup to get the image tag with class avatar **AND** avatar-user. This will return us a list of all the image tags with this class. We need to get the first element of the list and get its src.

So, our entire code is now :

```python
import requests
from bs4 import BeautifulSoup as bs

def get_profile_image(username) -> str:
    url = f"https://github.com/{username}/"
    res = requests.get(url)
    soup = bs(res.content, 'html.parser')
    profile_image = soup.select('img.avatar.avatar-user')[0]['src']
    return profile_image


if __name__ == "__main__":
    github_username = input("Enter Github Username : ")
    print(get_profile_image(github_username))
```

**Note**: This code cannot be used later since the HTML content may change in future.

## Renaming Bulk Files

In this project, we are going to write a Python program to rename all files within a folder. First, let's create a folder named demo and put three text files named **file1.txt**, **file2.txt** and **file3.txt** .  Let's start coding this.

First, we need to import the **os** library.

```python
import os
```

Let's create a function to function called **rename\_files** which takes an argument path.

```python
def rename_files(path):
    i = 0
    for file in os.listdir(path):
        new_name = f"Hello{i}.txt"
        src = path+file
        new_name = path+new_name
        os.rename(src, new_name)
        i += 1

```

In this method, we will iterate over all the files within a given path and use the rename method in os to rename it with the new name given by **f"Hello{i}.txt"**. We are using i as an increment variable.

So, the entire code is now :

```python
import os


def rename_files(path):
    i = 0
    for file in os.listdir(path):
        new_name = f"Hello{i}.txt"
        src = path+file
        new_name = path+new_name
        os.rename(src, new_name)
        i += 1


if __name__ == "__main__":
    rename_files("Renaming-Bulk-Files/demo/")

```

After running the program, all the files will be renamed as **Hello1.txt**, **Hello2.txt,** and **Hello3.txt** respectively.

## Getting Weather Information

In this project, we are building a weather program that will tell the current weather situations in a city or town or any location. So, for us to do this, we will be using [Open Weather Maps API](https://openweathermap.org/api). Just signup for free and get an API Key. We'll require `requests` library for this too, and we have already installed that.

Let's start coding.

First, we need to import the libraries :

```python
import requests
from pprint import pprint

```

When we make a request on the API, it responds with JSON data which is not easy to read, So, the `pprint` (pretty-print) library will make JSON data readable.

Also, set the below two global variables :

```python
API_KEY = '1e121683f8158a495a3414b71abcdef'
BASE_URL = 'https://api.openweathermap.org/data/2.5/weather'
```

You can get the API Key and Base URL from the above-mentioned site.

Now, let's create a function to get the weather data.

```python
def get_weather_condition(city):
    query_params = {
        'appid': API_KEY,
        'q': city
    }
    res = requests.get(BASE_URL, params=query_params).json()
    pprint(res)
```

In the above function, we are first creating a query params dictionary having two key-value pairs called `appid` and `q` where `appid` is the API Key and `q` is the city which we want to query. Then we are making a GET request to the Base URL with query\_params as params and thus our resultant URL will become:

```bash
https://api.openweathermap.org/data/2.5/weather?appid=API_KEY&q=city
```

We will get a JSON response and hence we are using the `pprint` library to make it readable. Our response will look like this :

```json
{
  "base": "stations",
  "clouds": { "all": 75 },
  "cod": 200,
  "coord": { "lat": 24.7833, "lon": 85 },
  "dt": 1622302757,
  "id": 1271439,
  "main": {
    "feels_like": 303.06,
    "humidity": 83,
    "pressure": 1004,
    "temp": 300.1,
    "temp_max": 300.1,
    "temp_min": 300.1
  },
  "name": "Gaya",
  "sys": {
    "country": "IN",
    "id": 9115,
    "sunrise": 1622244683,
    "sunset": 1622293424,
    "type": 1
  },
  "timezone": 19800,
  "visibility": 2000,
  "weather": [
    {
      "description": "broken clouds",
      "icon": "04n",
      "id": 803,
      "main": "Clouds"
    }
  ],
  "wind": { "deg": 0, "speed": 0 }
}
```

We can see that it responds with the current weather conditions of the city that we asked the data for. We can use this program anywhere like in a GUI application or a web application.

So, our complete program looks like :

```python
import requests
from pprint import pprint

API_KEY = '1e121683f8158a495a3414b7abcdef'
BASE_URL = 'https://api.openweathermap.org/data/2.5/weather'


def get_weather_condition(city):
    query_params = {
        'appid': API_KEY,
        'q': city
    }
    res = requests.get(BASE_URL, params=query_params).json()
    pprint(res)


if __name__ == "__main__":
    city = input("Enter city name : ")
    get_weather_condition(city)

```

## Password Generator

In this project, we are going to build a Password Generator that will generate random passwords of some length.

![](https://res.cloudinary.com/dlomjljb6/image/upload/v1/media/blog/uploads/2021/05/29/screenshot-2%5Fswpspz)

In this project, we'll be making use of Python's `secrets` module and `string` module. So, first, we need to import them as :

```python
from secrets import choice
import string
```

Since we'll be using only the choice method from `secrets` module, we have imported it explicitly.

Let's declare some global variables that we are going to use :

```python
UPPERCASE = string.ascii_uppercase
LOWECASE = string.ascii_lowercase
NUMBER = string.digits
SYMBOLS = ['@', '#', '$', '%', '&', '_']
DATA = list(UPPERCASE) + list(LOWECASE) + list(NUMBER) + SYMBOLS
```

Using the string library, we are creating three variables that contain **Uppercase letters**, **Lowercase letters,** and **Digits** respectively. Apart from that, we are having a **Symbols** list that has a few symbols. Using all of these four, we are creating a list called **DATA** that we'll be making use of.

Now, let's create a method called **generate_random\_password** that takes two arguments: **length** and **number**.

```python
def generate_random_password(length, number):
    print(f"Here are your {number} passwords of length {length} characters :\n")
    for _ in range(number):
        password = ''.join(choice(DATA) for _ in range(length))
        print(password)
```

Now we are creating a password using the **choice** method that generates a random string of length **length** using the **DATA** list. We are repeating the same for the **number** number of times.

So, our complete program now looks like this:

```python
from secrets import choice
import string

UPPERCASE = string.ascii_uppercase
LOWECASE = string.ascii_lowercase
NUMBER = string.digits
SYMBOLS = ['@', '#', '$', '%', '&', '_']
DATA = list(UPPERCASE) + list(LOWECASE) + list(NUMBER) + SYMBOLS


def generate_random_password(length, number):
    print(f"Here are your {number} passwords of length {length} characters :\n")
    for _ in range(number):
        password = ''.join(choice(DATA) for _ in range(length))
        print(password)


if __name__ == "__main__":
    number = int(input("How many passwords do you wish to generate ? : "))
    length = int(input("What should be the length of each password ? : "))
    generate_random_password(length, number)

```

## QR Codes in Python

In this project, we'll be talking about encoding and decoding QR Codes in Python.

Let's start by first encoding a QR Code and by encoding we mean, adding some data to a QR Code. For this, we have several libraries in Python but we'll be making use of `qrcode` library. Also, this library requires Pillow internally. So, first, we need to install these packages :

```bash
pip install qrcode Pillow
```

Now we can use the `qrcode` module to create a QR Code.

```python
def encode_qr(data):
    qr = qrcode.QRCode(version=1, box_size=10, border=5)
    qr.add_data(data)
    qr.make(fit=True)
    img = qr.make_image(fill_color='black', back_color='white')
    img.save('QR-Codes-in-Python/qrcode.png')
```

In the above function, we are first defining the version, box%5Fsize, and border of the QR code and then adding the data into it. We want a standard QR Code and hence set the colors to black and white and then we are saving the QR code as a PNG image file. Learn more about QR Codes [here](https://en.wikipedia.org/wiki/QR%5Fcode).![](https://res.cloudinary.com/dlomjljb6/image/upload/v1/media/blog/uploads/2021/05/29/qrcode%5Fulwlfp)

Now, let's decode the same QR code. For this, we require another library called `pyzbar`. So let's install this.

```python
pip install pyzbar
```

Then we can import libraries and create a `decode_qr` function as :

```python
from pyzbar.pyzbar import decode
from PIL import Image

def decode_qr(image):
    img = Image.open(image)
    result = decode(img)
    print(result)
```

This is a simple function that will decode the QR code immediately.

So our complete code becomes :

```python
import qrcode
from pyzbar.pyzbar import decode
from PIL import Image


def encode_qr(data):
    qr = qrcode.QRCode(version=1, box_size=10, border=5)
    qr.add_data(data)
    qr.make(fit=True)
    img = qr.make_image(fill_color='black', back_color='white')
    img.save('QR-Codes-in-Python/qrcode.png')


def decode_qr(image):
    img = Image.open(image)
    result = decode(img)
    print(result)


if __name__ == "__main__":
    encode_qr(data=f"Please share this post if you liked this blog.")
    decode_qr('QR-Codes-in-Python/qrcode.png')
```

## Conclusion

I hope, you liked the projects. You can get all the codes [here](https://github.com/ashutoshkrris/5-Python-Projects).
