A quick reference to Python
Created on: 2019-09-29
Tag: cheat_sheet
Warning
under heavy construction and not well organized
for i in range(11): print (something, end='\r')
import requests url = 'http://download.thinkbroadband.com/5MB.zip' fileName = '5MB.zip' req = requests.get(url) file = open(fileName, 'wb')
(source: http://stackoverflow.com/a/34863581/5350059)
OR:
import requests # open in binary mode url = 'http://download.thinkbroadband.com/5MB.zip' fileName = '5MB.zip' with open(fileName, "wb") as file: # get request response = requests.get(url) # write to file file.write(response.content)
import time start_time = time.time() main() print("--- %s seconds ---" % (time.time() - start_time))
import os os.remove("/tmp/<file_name>.txt")
don't forget to import os
newpath = r'C:\Program Files\arbitrary' if not os.path.exists(newpath): os.makedirs(newpath)
with open ("test.txt","w")as fp: for line in list12: fp.write(line+"\n")
lines_list = open('file.txt').read().splitlines()
def recursive_overwrite(src, dest, ignore=None): if os.path.isdir(src): if not os.path.isdir(dest): os.makedirs(dest) files = os.listdir(src) if ignore is not None: ignored = ignore(src, files) else: ignored = set() for f in files: if f not in ignored: recursive_overwrite(os.path.join(src, f), os.path.join(dest, f), ignore) else: shutil.copyfile(src, dest)
print('\033[91m' + "message" + '\033[0m')
print os.path.basename(your_path)
string = "trick or treat" for c in string[::-1]: print c
import termcolor string = "type-name-function-location" string = string.replace('-', termcolor.colored('-', 'red')) print string
import os def clear(): os.system('cls' if os.name=='nt' else 'clear') #call the function clear()
(source: https://stackoverflow.com/a/684344)
#python2 raw_input("Press Enter to continue...") #python3 input("Press Enter to continue...")
(source: https://stackoverflow.com/a/983382)
try: import mymodule except ImportError, e: pass # module doesn't exist, deal with it.
import pyttsx3 engine = pyttsx3.init() engine.say("Hello this is me talking") engine.setProperty('rate',120) #120 words per minute engine.setProperty('volume',0.9) engine.runAndWait()
(source: https://stackoverflow.com/a/44752880)
>>>int("১") 1
(source: https://www.facebook.com/groups/pythonbd/permalink/1182034515231297/)
import sys sys.exit()
# Python code to illustrate Sending mail with attachments # from your Gmail account # libraries to be imported import smtplib from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.mime.base import MIMEBase from email import encoders fromaddr = "EMAIL address of the sender" toaddr = "EMAIL address of the receiver" # instance of MIMEMultipart msg = MIMEMultipart() # storing the senders email address msg['From'] = fromaddr # storing the receivers email address msg['To'] = toaddr # storing the subject msg['Subject'] = "Subject of the Mail" # string to store the body of the mail body = "Body_of_the_mail" # attach the body with the msg instance msg.attach(MIMEText(body, 'plain')) # open the file to be sent filename = "File_name_with_extension" attachment = open("Path of the file", "rb") # instance of MIMEBase and named as p p = MIMEBase('application', 'octet-stream') # To change the payload into encoded form p.set_payload((attachment).read()) # encode into base64 encoders.encode_base64(p) p.add_header('Content-Disposition', "attachment; filename= %s" % filename) # attach the instance 'p' to instance 'msg' msg.attach(p) # creates SMTP session s = smtplib.SMTP('smtp.gmail.com', 587) # start TLS for security s.starttls() # Authentication s.login(fromaddr, "Password_of_the_sender") # Converts the Multipart msg into a string text = msg.as_string() # sending the mail s.sendmail(fromaddr, toaddr, text) # terminating the session s.quit()
(source: https://www.geeksforgeeks.org/send-mail-attachment-gmail-account-using-python/)
to see the package install location:
pip show <package name>
to build regex with variable or as string:
regex = r"^([" + re.escape(string_or_var) + r"][" + re.escape(string_or_var) + r"]+)"
to find all string that matches a regex:
re.findall(regex,string)
to repeat string:
print(deltimiter.join([string[:slice]] * times))
example:
string = 'Hello There' print(' '.join([string[:5]] * 2)) >>> Hello Hello
source: https://stackoverflow.com/a/17183278/5350059
OR
use this:
"Hello world " * 2 >>> 'Hello world Hello world '
to access command line arguments:
import sys print(sys.argv)
Note
sys.argv is a list where sys.argv[0] is the program name.
to check if argument is empty:
if len(sys.argv) == 1: # do stuff
to check if a list is empty:
if not a: print("List is empty")
to get full path from file and directory name:
os.path.join(dir_name, base_filename + "." + filename_suffix)
to iterate over files in a directory:
import os for filename in os.listdir(directory): if filename.endswith(".asm") or filename.endswith(".py"): # print(os.path.join(directory, filename)) continue else: continue
Django supports bash auto-completion. for this first download auto-completion script:
wget -O ~/.django_bash_completion.sh https://raw.github.com/django/django/master/extras/django_bash_completion
Modify bashrc to add auto-completion script:
source $HOME/.django_bash_completion.sh
Reload latest bashrc:
source ~/.bashrc
source: http://www.indjango.com/ubuntu-django-bash-auto-completion/
to install package from inside python shell:
from pip._internal import main as _main package_names=['pandas'] #packages to install _main(['install'] + package_names + ['--upgrade'])
to print bold text:
print('\033[1m' + 'Hello World !' + '\033[0m')
We can do more tricks:
class color: PURPLE = '\033[95m' CYAN = '\033[96m' DARKCYAN = '\033[36m' BLUE = '\033[94m' GREEN = '\033[92m' YELLOW = '\033[93m' RED = '\033[91m' BOLD = '\033[1m' UNDERLINE = '\033[4m' END = '\033[0m' print(color.BOLD + 'Hello World !' + color.END)
to get all object attributes of a object:
object.dir()
to beautify JSON in Python:
echo '{"one":1,"two":2}' | python -mjson.tool
to create a django secret key with bash:
export SECRET_KEY=$(head /dev/urandom | tr -dc 'A-Za-z0-9!"#$%&'\''()*+,-./:;<=>?@[\]^_`{|}~' | head -c 49 ; echo '')
Kept also in the Bash Cheat Sheet as it is relevant.
source: How to generate a random string?
to read dictionary in pandas:
# the dictionary examinee = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'], 'scores': [12.5, 9, 16.5, 2.3, 9, 20, 14.5, 4.5, 8, 19], 'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1], 'qualified': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']} # now let's load the dictionary in pandas df = pd.DataFrame.from_dict(examinee)
source: pandas.DataFrame.from_dict
to print a column in pandas:
print(df.Name.to_string(index=False))
Output:
Adam Bob Cathy
source: Display/Print one column from a DataFrame of Series in Pandas
to see heading columns in pandas:
# for a dataframe df = pd.DataFrame({'animal':['alligator', 'bee', 'falcon', 'lion', 'monkey', 'parrot', 'shark', 'whale', 'zebra']}) # now print the heading aka the first 5 lines df.head() # output animal 0 alligator 1 bee 2 falcon 3 lion 4 monkey
source: pandas.DataFrame.head
to do a dot matrix of two numpy array:
numpy.dot($ARRAY_A,$ARRAY_B)
source: NumPy v1.17 Manual: numpy.dot
to convert character to integer:
>>> ord('a') 97
to convert integer to character:
>>> chr(97) 'a'
to check if string is upper case:
>>> "AaBC".isupper() False >>> "ABC".isupper() True >>>
d = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d') print datetime.date.strftime(d, "%m/%d/%y")
import json with open('strings.json') as f: d = json.load(f) print(d)