list of python examples¶
handling text files¶
handling text files is very easy.
check below code to open and read any text file.
In [ ]:
Copied!
# open, read lines and print
text_file = '_data/dummy_file.txt'
with open(text_file, 'r') as fh:
text_file_content = fh.readlines()
print(*text_file_content)
# open, read lines and print
text_file = '_data/dummy_file.txt'
with open(text_file, 'r') as fh:
text_file_content = fh.readlines()
print(*text_file_content)
handling csv files using pandas¶
In [ ]:
Copied!
# install pandas
%pip install pandas
# install pandas
%pip install pandas
In [ ]:
Copied!
# import package
import pandas as pd
# read csv file
csv_file = '_data/random_data_from_web.csv'
csv_data = pd.read_csv(csv_file)
# fetch and print one of the column values
customer_ids = csv_data['Customer Id']
print(customer_ids)
# import package
import pandas as pd
# read csv file
csv_file = '_data/random_data_from_web.csv'
csv_data = pd.read_csv(csv_file)
# fetch and print one of the column values
customer_ids = csv_data['Customer Id']
print(customer_ids)
open site url in default web browser¶
In [ ]:
Copied!
# import package
import webbrowser
# open url using the default browser
site_url = 'https://github.com/chaitu-ycr/python_notes'
webbrowser.open(url=site_url)
# import package
import webbrowser
# open url using the default browser
site_url = 'https://github.com/chaitu-ycr/python_notes'
webbrowser.open(url=site_url)
create simple GUI using tkinter¶
In [ ]:
Copied!
# import package
import tkinter as tk
class GUI(tk.Tk):
def __init__(self):
super().__init__()
self.title("Hello Button Example")
# Set the window size (width x height)
self.geometry("200x100") # Adjust the dimensions as needed
# Create a button
clickButton = tk.Button(self, text='PressMe😋', command=self.say_hello)
clickButton.pack()
# Create a label
self.textLabel = tk.Label(self, text="Press Button to say Hello...")
self.textLabel.pack()
def say_hello(self):
# Update the label with text
self.textLabel.configure(text='Helooo..😴')
# Create an instance of the GUI class
gui = GUI()
# Start the GUI event loop
gui.mainloop()
# import package
import tkinter as tk
class GUI(tk.Tk):
def __init__(self):
super().__init__()
self.title("Hello Button Example")
# Set the window size (width x height)
self.geometry("200x100") # Adjust the dimensions as needed
# Create a button
clickButton = tk.Button(self, text='PressMe😋', command=self.say_hello)
clickButton.pack()
# Create a label
self.textLabel = tk.Label(self, text="Press Button to say Hello...")
self.textLabel.pack()
def say_hello(self):
# Update the label with text
self.textLabel.configure(text='Helooo..😴')
# Create an instance of the GUI class
gui = GUI()
# Start the GUI event loop
gui.mainloop()
create simple browser based user interface page using dash¶
In [ ]:
Copied!
# import package
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
# Create a Dash app
app = dash.Dash(__name__)
# Define the layout
app.layout = html.Div([
html.Button("Say Hello", id="hello-button"),
html.H3(id="output-label")
])
# Callback to update the label when the button is pressed
@app.callback(
Output("output-label", "children"),
[Input("hello-button", "n_clicks")]
)
def update_label(n_clicks):
if n_clicks:
return "Hello, World!"
else:
return ""
if __name__ == "__main__":
app.run_server(debug=True)
# import package
import dash
from dash import dcc
from dash import html
from dash.dependencies import Input, Output
# Create a Dash app
app = dash.Dash(__name__)
# Define the layout
app.layout = html.Div([
html.Button("Say Hello", id="hello-button"),
html.H3(id="output-label")
])
# Callback to update the label when the button is pressed
@app.callback(
Output("output-label", "children"),
[Input("hello-button", "n_clicks")]
)
def update_label(n_clicks):
if n_clicks:
return "Hello, World!"
else:
return ""
if __name__ == "__main__":
app.run_server(debug=True)
open images using opencv and pillow¶
In [ ]:
Copied!
# install packages
%pip install opencv-python
# install packages
%pip install opencv-python
example 1: opening local image using opencv¶
In [ ]:
Copied!
# import package
import cv2
# Read an image from a file
image_path = "_data/dummy_image.jpg" # Replace with the actual path to your image
img = cv2.imread(image_path, cv2.IMREAD_COLOR)
# Check if the image was loaded successfully
if img is not None:
# Display the image in a window
cv2.imshow("Image", img)
cv2.waitKey(0) # Wait for a key press (0 means indefinitely)
cv2.destroyAllWindows() # Close the window
else:
print("Error loading the image. Please check the file path.")
# import package
import cv2
# Read an image from a file
image_path = "_data/dummy_image.jpg" # Replace with the actual path to your image
img = cv2.imread(image_path, cv2.IMREAD_COLOR)
# Check if the image was loaded successfully
if img is not None:
# Display the image in a window
cv2.imshow("Image", img)
cv2.waitKey(0) # Wait for a key press (0 means indefinitely)
cv2.destroyAllWindows() # Close the window
else:
print("Error loading the image. Please check the file path.")
example 2: opening online image using pillow¶
In [ ]:
Copied!
# import package
from PIL import Image
import requests
from io import BytesIO
# Replace the URL with the actual image URL
url = "https://picsum.photos/200"
# Fetch the image data from the URL
response = requests.get(url)
image_data = BytesIO(response.content)
# Open the image using PIL
image = Image.open(image_data)
# Display the image
image.show()
# import package
from PIL import Image
import requests
from io import BytesIO
# Replace the URL with the actual image URL
url = "https://picsum.photos/200"
# Fetch the image data from the URL
response = requests.get(url)
image_data = BytesIO(response.content)
# Open the image using PIL
image = Image.open(image_data)
# Display the image
image.show()