Open In App

Top 12 Python Scripts For Developers to Implement

Last Updated : 29 Mar, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python is a widely used high-level, general-purpose programming language.  This language can be used in web development, machine learning applications, and all cutting-edge software technology and is preferred for both beginners as well as experienced software developers. Developers spent most of their time developing or working with scripts. Python Scripts are a set of python programs that are developed to perform a specific task. 

Python Scripts for Developers

 

Working with these scripts offer a convenient and efficient way to automate repetitive tasks, process large amounts of data, and perform complex computations. As Python is a high-level programming language, which means that it abstracts away many of the low-level details that are involved in writing code, which makes the Scripts easier to write and maintain. With this being said let’s continue the article on the best Python Scripts to assist you to have a much easier time learning & building with Python. 

Top 12 Python Scripts for Developers to Implement

1. Password Checker

The below script checks whether the provided password is weak or strong based on the predefined constraints.

Python




import re
def check_password(password):
  if len(password) < 8:
    return False
  elif re.search('[0-9]',password) is None:
    return False
  elif re.search('[a-z]',password) is None:
    return False
  elif re.search('[A-Z]',password) is None:
    return False
  elif re.search('[@#$^&]',password) is None:
    return False
  return True
      
for password in ["12345678", "Abcd@1234"]:
  if(check_password(password)):
    print(password, " is a strong password.")
  else:
    print(password, "is a weak password.")


Output:

12345678 is a weak password.
Abcd@1234  is a strong password.

In the above implementation, the Scripts evaluates the password as strong only if:

  • length of the password is greater than 8.
  • password has at least 1 digit.
  • password has at least 1 upper case & lower case character.
  • password has at least 1 special character from ” @#$^&“.

Must Read: Regex in Python

2. Password encryption & decryption

The below script performs encryption and decryption of text using the cryptography package.

Python




from cryptography.fernet import Fernet
  
def encrypt(text, key):
    f = Fernet(key)
    encrypted_text = f.encrypt(text.encode())
    return encrypted_text
  
def decrypt(encrypted_text, key):
    f = Fernet(key)
    decrypted_text = f.decrypt(encrypted_text).decode()
    return decrypted_text
  
text = "user_text"
key = Fernet.generate_key()
encrypted_text = encrypt(text, key)
print("Encrypted text: ", encrypted_text)
  
decrypted_text = decrypt(encrypted_text, key)
print("Decrypted text: ", decrypted_text)


Output:

Encrypted text:  b'gAAAAABj61UjSdV92kh_ahTNK_dKgpcWHyHpAKVtbR05UWnMEE-pbYGI2E_tkDG2LOPPEt4kksfsTpXFwquVPBrETYy1foFGEg=='
Decrypted text:  user_text

In the above implementation, the encryption key is generated using the Fernet.generate_key() method and is stored in a file for future use. The encryption and decryption of text are done using the Fernet class from the cryptography package, where the text is encrypted using the encrypt() method and decrypted using the decrypt() method.

Must Read: Encryption & Decryption | python

3. Fetching current news

The below script fetches the current news from NewsAPI. Implementation can be modified depending on the use case.

Python




# $ pip install newsapi-python
from newsapi import NewsApiClient
  
newsapi = NewsApiClient(api_key='API_KEY')
  
# /v2/top-headlines
top_headlines = newsapi.get_top_headlines(language='en', country='in')
  
for article in top_headlines["articles"]:
  title = article["title"]
  print(f"Title: {title}\n")


Output:

Title: I-T teams at BBC's Delhi, Mumbai offices for survey as part of tax evasion investigation -
 India Today

Title: "Smriti Mandhana's Salary More Than Babar Azam's": 
WPL Auction Sees Memes Galore On Social Media - NDTV Sports

Title: Male Infertility: Can Lifestyle Changes Boost Fertility? - NDTV

Title: BREAKING| Congress Leader Moves Supreme Court For Investigation 
Against Adani Group Based On Hindenburg... - Live Law - Indian Legal News

Title: WPI inflation cools to 24-month low of 4.73% in January | Mint - Mint

In the above implementation, the script makes use of newsapi-python package to fetch the current news. The script loops through each article in the response and prints the title of each article. Note that you will need to obtain an API key from the News API website in order to use the API. 

4. Sending Emails

The below script uses the `SMTP library to send an email to the provided receiver/’s. Implementation can be modified depending on the use case.

Python




import smtplib
  
def send_email(sender, receiver, password, subject, message):
    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.ehlo()
    server.starttls()
    server.ehlo()
    server.login(sender, password)
    message = f"Subject: {subject}\n\n{message}"
    server.sendmail(sender, receiver, message)
    print("Email sent!")
    server.quit()
  
sender = "SENDER_ADDRESS"
receiver = "RECEIVER_ADDRESS"
password = "APP_PASSWORD"
subject = "Hello From GFG"
message = "Message Body"


In the above implementation, the script takes the sender and the receiver’s details as well as the message subject and body. The script then connects to Gmail’s SMTP server, formats the message, and sends it via the sendmail() method. Finally, the script prints a message indicating that the email was successfully sent and disconnects from the SMTP server.

Must Read: smtplib in Python

5. URL Shortener

The below script uses ‘TinyURL API’  to shorten the provided URL.

Python3




import requests
  
def shorten_url(url):
    response = requests.get("http://tinyurl.com/api-create.php?url="+url)
    return response.text
  
short_url = shorten_url(url)
print(f"The shortened URL is: {short_url}")


Output:

The shortened URL is: https://tinyurl.com/2bqwr25r

In the above implementation, the shorten_url() function takes the URL that is to be shortened and returns the shortened URL. Inside the shorten_url() function requests library is used to make a GET request to the TinyURL API. The ‘response.text’ attribute from the response received by the API contains the shortened URL.

Must Read: URL shortener in Python

6. Generating a QR code for the data

The below script uses ‘qrcode’ library in Python, to generate the QR code of the provided data.

Python3




import qrcode
  
def generate_qr_code(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_code.png")
    print("QR code generated!")
  
data = 'Data to be encoded'
generate_qr_code(data)


Output:

 

In the above implementation, the generate_qr_code() function generates and saves the QR code for the provided data. Inside the generate_qr_code() function, it first creates a QRCode object, adds data to it, and then generated the image for the QRCode using make_image() method. The image is then saved by the name of “qr_code.png”. Finally “QR code generated!” message is printed, indicating the successful execution of the script.

Must Read: QRCode in Python

7. Text to Speech

The below script uses the ‘gTTg’ library in python, is to convert the provided text into a speech format.

Python3




from gtts import gTTS
import os
  
def say(text):
  tts = gTTS(text=text, lang='en')
  tts.save("geeks.mp3")
  
  os.system("mpg321 geeks.mp3")
    
say("Hello, Geeks for Geeks!")


In the above implementation, the say() function takes in the text to be converted and input. The text and language of the text are then passed as parameters to the gTTS() function. The resulting speech is then saved to an mp3 file “geeks.mp3“. Finally, using the mpg321 command line tool, the os.system() function is used to play the mp3 file.

Must Read: Text to Speech in Python

8. Convert jpg to png (and vice-versa)

The below script uses the ‘pillow’ library in python, to convert an Image (.jpg) file to .png file ( and vice-versa ) in Python.

Python3




from PIL import Image
  
# To convert the Image From JPG to PNG
def jpg_to_png(IMG_PATH):
  img = Image.open(IMG_PATH).convert('RGB')
  img.save("Image_1.png", "PNG")
   
# To convert the Image From PNG to JPG
def png_to_img(PNG_PATH):
  img = Image.open(PNG_PATH).convert('RGB')
  img.save("Image_1.jpg", "JPEG")
  
png_to_img("file.png")
jpg_to_png("Image.jpg")


Output:

 

In the above implementation, the script defines 2 functions one for converting jpg to png and another one for converting png to jpg. Initially, the Image class from the PIL library is imported, then 2 functions are defined which tend to follow a similar approach wherein firstly,  the image file (IMG_PATH) is opened using the Image.open() method. The resulting image object is then saved as a PNG/JPG file using the img.save() method. The method also has a second parameter as “PNG”/”JPEG” to specify the format.

Must Read: PIL in Python

9. Convert CSV to excel

The below script uses the ‘pandas’ library in python, to convert a CSV to an Excel file in Python.

Python3




import pandas as pd
  
def csv_to_excel(FILE_PATH):
  df = pd.read_csv(FILE_PATH)
  df.to_excel("file.xlsx", index=False)
try:
    csv_to_excel("disk_usage.csv")
    print("File Created")
except:
    print("Something wrong")


Output:

File Created

In the above implementation, after importing the pandas library, the csv_to_excel() function is defined which takes in the CSV file path as the input. The CSV file (“gfg.csv”) is read into a pandas DataFrame using the read_csv() method. The resulting DataFrame is then saved to an Excel file using the to_excel() method, which takes  “file.xlsx” as the first argument to specify the name of the Excel file, and index=False to exclude the DataFrame index from the output.

Must Read: CSV to Excel in Python

10. Extracting data from phone number

The below script uses the ‘phonenumbers’ library in python, to extract details about the phone number in Python.

Python3




import phonenumbers
from phonenumbers import timezone, geocoder, carrier
    
# Parsing String to Phone number
def get_phone_data(number):
  phoneNumber = phonenumbers.parse(number)
  return {
      "baisc-data": phoneNumber,
      "time-zone": timezone.time_zones_for_number(phoneNumber),
      "career": carrier.name_for_number(phoneNumber, 'en'),
      "is_valid": phonenumbers.is_valid_number(phoneNumber),
      "is_possible": phonenumbers.is_possible_number(phoneNumber)
  }
  
print(get_phone_data("+91XXXXXXXXXX"))


Output:

{'baisc-data': PhoneNumber(country_code=91, national_number=9********, extension=None, 
italian_leading_zero=None, number_of_leading_zeros=None, country_code_source=0, 
preferred_domestic_carrier_code=None), 'time-zone': ('Asia/Calcutta',),
 'career': 'Aircel', 'is_valid': True, 'is_possible': True

In the above implementation, the script first imports all the necessary libraries and classes required to extract the data. The function get_phone_data() takes a phone number as an argument and uses the parse() method from the phonenumbers library to parse the phone number into a phoneNumber object. The function returns an object which contains basic details like country code and extracted national number, the time zone to which the number belongs, the career name of the number, a boolean value that indicates if the number is valid, and another boolean value that indicates if the number is possible.

Must Read: Phonenumbers Module in Python

11. Fetching Crypto Currency Price

The below script uses ‘Alpha Vantage’ API to fetch the data about the current Crypto price in python. The implementation can be modified to get information about stocks, forensics as well as cryptocurrencies

Python3




import requests
  
# get your free api key from : https://www.alphavantage.co/support/#api-key
API_KEY = "YOUR_API_KEY"
def get_current_price(SYMBOL):
  url = "https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency="+SYMBOL+"&to_currency=USD&apikey=" + API_KEY
  response = requests.get(url)
  data = response.json()  
  return float(data["Realtime Currency Exchange Rate"]["5. Exchange Rate"])
  
symbol = "BTC"
print("The current price of",symbol,"is",get_current_price("BTC"))


Output:

The current price of BTC is 21804.17

In the above implementation, the script defines a function get_current_price() that takes a cryptocurrency symbol (i.e. “BTC”) as an input and returns its current price in US dollars. The function starts by constructing an API URL for the Alpha Vantage API, which includes the cryptocurrency SYMBOL, and an API key stored as the API_KEY constant. After making an API request to the Alpha Vantage API, the response from the API is stored in the response variable, which is then converted to a Python dictionary using the json() method.  The cryptocurrency price is then extracted from the dictionary using keys such as “Realtime Currency Exchange Rate” and “5. Exchange Rate”, and returned by the get_current_price function.

12. GeoCoding and Reverse GeoCoding

The following script performs geocoding and reverse-geocoding with the help of the geopy library in python.

Python3




from geopy.geocoders import Nominatim
  
def print_data(location):
  print("Address: ",location.address)
  print("Latitude: ", location.latitude)
  print("Longitude: ",location.longitude)
  
geolocator = Nominatim(user_agent="gfg_app")
  
def geocoding(address):
  location = geolocator.geocode(address)
  print_data(location)
  
def rev_geocoding(latitude_longitude):
  location = geolocator.reverse(latitude_longitude)
  print_data(location)
  
geocoding("175 5th Avenue NYC")
rev_geocoding("52.509669, 13.376294")


Output:

Address:  Flatiron Building, 175, 5th Avenue, Manhattan Community Board 5,
         Manhattan, New York County, City of New York, New York, 10010, United States
Latitude:  40.741059199999995
Longitude:  -73.98964162240998
Address:  Steinecke, Potsdamer Platz, Tiergarten, Mitte, Berlin, 10785, Deutschland
Latitude:  52.5098134
Longitude:  13.37631790998454

In the above implementation, the script uses the geopy library to perform geocoding and reverse geocoding operations. The script defines two functions geocoding() and rev_geocoding() to perform these two operations. The geocoding() function takes an address as an input and uses the Nominatim class from the geopy library to perform geocoding. The rev_geocoding() function takes latitude and longitude coordinates as input and performs reverse geocoding.  Both functions use the print_data() function to display the results of the geocoding/reverse geocoding operations, including the address, latitude, and longitude.

Must Read: geopy in Python

Conclusion

Python is a versatile and widely-used programming language, making it a great choice for developers to implement scripts for a variety of purposes. This article highlights some of the most useful and practical scripts that developers can use to automate tasks, process data, and perform various functions. Whether you are a beginner or an experienced developer, these scripts provide a good starting point for leveraging the power of Python. Finally, the best script for a specific task will depend on the project’s specific requirements and goals, so it’s critical to evaluate and customize these scripts as needed to fit your needs.

FAQs

1. What is Python and what is it used for?

Python is a high-level, interpreted programming language that was first released in 1991.  It’s used for a variety of tasks, including web development, data analysis, machine learning, scientific computing, and more.

2. What is a Python Script?

Python scripts are programs written in Python. The Python interpreter runs it line by line and can be used to automate tasks, process data, and perform various functions.

3. How to run a Python script?

You can run a Python Script by opening the terminal or command prompt, navigating to the directory where the script is located, and typing “python script.py” (where “script.py” is the name of your script).



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads