Python - The Elite List


Import table from .csv file in PostgreSQL using Pandas

import pandas as pd
df = pd.read_csv('table.csv')
df.columns = [c.lower() for c in df.columns]

from sqlalchemy import create_engine
engine = create_engine('postgresql://user:pass@host:5432/db_name')

df.to_sql("table_name", engine)

Search and Replace a word in the file using Python

# Read and save file content
with open('file.txt', 'r') as file :
    filedata = file.read()
    # Replace words with new ones.
    filedata = filedata.replace('abc', 'def')
# Overwrite the file with new contents
with open('file.txt', 'w') as file:
    file.write(filedata)

Install virtualenv for Python3

sudo apt-get install python3-pip
sudo pip3 install virtualenv
virtualenv -p python3 myenv
source venv/bin/activate

Unzip file using Python's zipfile.

# Unzip file - check.zip
import zipfile
with zipfile.ZipFile("check.zip","r") as zip_ref:
    zip_ref.extractall("check_data")