Python >> Tips and Tricks 5
Table of Contents
This tutorial will explain how to read and write files, how to use decorator, how to use defaultdict, how to sort, how to format string.
Python how to read and write files
Read file
# Read file
with open(r"D:\test\test2.txt", "r") as f:
content = f.read()
print(content)
test22222
test2222222
Write file
# Write file
with open(r"D:\test\test2.txt", "w") as f:
f.write("update test22222\nupdate test2222222")
Python how to use decorator
Decorator
# Decorator
def decorator_function(original_function):
def wrapper_function():
print("wrapper executed this before {}".format(original_function.__name__))
return original_function()
return wrapper_function
@decorator_function
def display():
print("display function ran")
display()
wrapper executed this before display
display function ran
Decorator with arguments
# Decorator with arguments
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print("wrapper executed this before {}".format(original_function.__name__))
return original_function(*args, **kwargs)
return wrapper_function
@decorator_function
def display(name):
print("display function ran with {}".format(name))
display("John")
wrapper executed this before display
display function ran with John
Decorator with arguments and return value
# Decorator with arguments and return value
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
print("wrapper executed this before {}".format(original_function.__name__))
return original_function(*args, **kwargs)
return wrapper_function
@decorator_function
def display(name):
print("display function ran with {}".format(name))
return "Hi {}".format(name)
display("John")
wrapper executed this before display
display function ran with John
'Hi John'
Python how to use defaultdict
Defaultdict with list as parameter
# Defaultdict
from collections import defaultdict
d = defaultdict(list)
d["a"].append(1)
d["a"].append(2)
d["b"].append(4)
d["b"].append(5)
print(d)
defaultdict(<class 'list'>, {'a': [1, 2], 'b': [4, 5]})
Defaultdict with int as parameter
# Defaultdict
from collections import defaultdict
d = defaultdict(int)
d["a"] += 1
d["a"] += 1
d["b"] += 1
d["c"] += 1
print(d)
defaultdict(<class 'int'>, {'a': 2, 'b': 1, 'c': 1})
Defaultdict with set as parameter
# Defaultdict
from collections import defaultdict
d = defaultdict(set)
d["a"].add(1)
d["a"].add(2)
d["b"].add(4)
d["b"].add(5)
d["b"].add(6)
print(d)
defaultdict(<class 'set'>, {'a': {1, 2}, 'b': {4, 5, 6}})
Python how to sort
Sort list using sort() method of list
# Sort list
l = [2, 9, 1, 4, 10, 6, 5, 7, 8, 3]
l.sort()
print(l)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sort list using sorted() method
# Sort list
l = [2, 9, 1, 4, 10, 6, 5, 7, 8, 3]
l2 = sorted(l)
print(l2)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sort set using sorted() method
# Sort set
s = {2, 9, 1, 4, 10, 6, 5, 7, 8, 3}
s2 = sorted(s)
print(s2)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Sort dictionary by key
# Sort dictionary by key
d = {"c": 1, "b": 2, "a": 3}
d2 = sorted(d.items())
print(d2)
[('a', 3), ('b', 2), ('c', 1)]
Sort dictionary by key descending
# Sort dictionary by key descending
d = {"c": 1, "b": 2, "a": 3}
d2 = sorted(d.items(), reverse=True)
print(d2)
[('c', 1), ('b', 2), ('a', 3)]
Sort dictionary by value
# Sort dictionary by value
d = {"c": 1, "b": 2, "a": 3}
d2 = sorted(d.items(), key=lambda kv: kv[1])
print(d2)
[('c', 1), ('b', 2), ('a', 3)]
Sort dictionary by value descending
# Sort dictionary by value descending
d = {"c": 1, "b": 2, "a": 3}
d2 = sorted(d.items(), key=lambda kv: kv[1], reverse=True)
print(d2)
[('a', 3), ('b', 2), ('c', 1)]
Python how to format string
Use format() method
# Use format() method
"{} {} {}".format("a", "b", "c")
a b c
Use f-string
# Use f-string
a = "a"
b = "b"
c = "c"
print(f"{a} {b} {c}")
a b c
Use % operator
# Use % operator
"%s %s %s" % ("a", "b", "c")
a b c