Fundamentals 9 min read

Python Practical Guide: File I/O, CSV, JSON, HTTP Requests, SQLite, Scheduling, Logging, Argument Parsing, Compression, Subprocess, DateTime, Email, Image Processing, NumPy, Pandas, Regex, System Info, Socket Programming, and AsyncIO

This comprehensive Python tutorial demonstrates essential techniques such as file reading and writing, CSV and JSON handling, HTTP requests, SQLite operations, task scheduling, logging, command‑line parsing, compression, subprocess management, date‑time handling, email sending, image manipulation, numerical computing, data analysis, regular expressions, system information retrieval, socket networking, and asynchronous programming.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Python Practical Guide: File I/O, CSV, JSON, HTTP Requests, SQLite, Scheduling, Logging, Argument Parsing, Compression, Subprocess, DateTime, Email, Image Processing, NumPy, Pandas, Regex, System Info, Socket Programming, and AsyncIO

1. File read/write:

with open('file.txt','r') as file:
    content = file.read()
print(content)

and

with open('output.txt','w') as file:
    file.write("Hello, World!")

2. CSV handling: read with

import csv
with open('data.csv','r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

; write with

import csv
data = [['Name','Age'],['Alice',30],['Bob',25]]
with open('output.csv','w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

3. JSON handling: read with

import json
with open('data.json','r') as file:
    data = json.load(file)
print(data)

; write with

import json
data = {'name':'Alice','age':30}
with open('output.json','w') as file:
    json.dump(data, file)

4. HTTP requests: GET with

import requests
response = requests.get('https://api.example.com/data')
if response.status_code == 200:
    print(response.json())
else:
    print(f"Request failed with status code: {response.status_code}")

; POST with

import requests
payload = {'key':'value'}
response = requests.post('https://api.example.com/submit', data=payload)
if response.status_code == 200:
    print(response.json())
else:
    print(f"Request failed with status code: {response.status_code}")

5. SQLite database:

import sqlite3
conn = sqlite3.connect('example.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS stocks (date text, trans text, symbol text, qty real, price real)''')
c.execute("INSERT INTO stocks VALUES ('2023-01-01','BUY','RHAT',100,35.14)")
conn.commit()
c.execute('SELECT * FROM stocks')
print(c.fetchall())
conn.close()

6. Scheduling tasks:

import schedule, time

def job():
    print("I'm working...")

schedule.every(10).seconds.do(job)
while True:
    schedule.run_pending()
    time.sleep(1)

7. Logging:

import logging
logging.basicConfig(filename='app.log', level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logging.info('This is an info message')
logging.warning('This is a warning message')
logging.error('This is an error message')

8. Command‑line argument parsing:

import argparse
parser = argparse.ArgumentParser(description='Process some integers.')
parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator')
parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)')
args = parser.parse_args()
print(args.accumulate(args.integers))

9. File compression:

import zipfile
with zipfile.ZipFile('archive.zip','w') as zipf:
    zipf.write('file.txt')

; extraction with

import zipfile
with zipfile.ZipFile('archive.zip','r') as zipf:
    zipf.extractall('.')

10. Subprocess execution:

import subprocess
result = subprocess.run(['ls','-l'], capture_output=True, text=True)
print(result.stdout)

11. Date and time:

from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S"))

12. Sending email:

import smtplib
from email.mime.text import MIMEText
msg = MIMEText('This is the body of the email')
msg['Subject'] = 'Hello'
msg['From'] = '[email protected]'
msg['To'] = '[email protected]'
with smtplib.SMTP('smtp.example.com', 587) as server:
    server.starttls()
    server.login('username','password')
    server.sendmail('[email protected]',["[email protected]"],msg.as_string())

13. Image processing:

from PIL import Image
img = Image.open('image.jpg')
img_resized = img.resize((800,600))
img_resized.save('resized_image.jpg')

14. Text replace:

text = "Hello, World!"
new_text = text.replace("World","Python")
print(new_text)

15. Numerical computation with NumPy:

import numpy as np
arr = np.array([1,2,3,4])
print(arr * 2)

16. Data analysis with Pandas:

import pandas as pd
df = pd.DataFrame({
    'Name': ['Alice','Bob','Charlie'],
    'Age': [25,30,35]
})
print(df.describe())

17. Regular expressions:

import re
pattern = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
text = "Contact us at [email protected]"
match = re.search(pattern, text)
if match:
    print(match.group())

18. System information:

import platform
print(platform.system())
print(platform.release())
print(platform.version())

19. Simple TCP server:

import socket
host = '127.0.0.1'
port = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((host, port))
    s.listen()
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)

20. Simple TCP client:

import socket
host = '127.0.0.1'
port = 65432
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((host, port))
    s.sendall(b'Hello, Server!')
    data = s.recv(1024)
print('Received', repr(data))

21. Asynchronous programming with asyncio:

import asyncio
async def my_coroutine():
    print("Starting coroutine")
    await asyncio.sleep(1)
    print("Coroutine finished")
async def main():
    task = asyncio.create_task(my_coroutine())
    await task
asyncio.run(main())
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythondata-processingprogrammingFile I/ONetworkingTutorial
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.