import uuid
filename = str(uuid.uuid4())
Best way to generate random file names in Python
my_dict.pop('key', None)
How to remove a key from a Python dictionary?
change json.loads
to json.load
python中读取json文件时报错,TypeError:the Json object must be str, bytes or bytearray,not ‘TextIOWrapper’
$ python -c "import math"
$ echo $?
0 # math module exists in system
$ python -c "import numpy"
Traceback (most recent call last):
File "<string>", line 1, in <module>
ImportError: No module named numpy
$ echo $?
1 # numpy module does not exist in system
from datetime import date, timedelta
# Let's say it's Monday
today = date.today()
# datetime.date(2020, 6, 15)
last_week_start = today - timedelta(days=today.weekday()+7)
# today.weekday() = 0
# datetime.date(2020, 6, 8)
# last_week_start.weekday() = 0
# str(last_week_start) = '2020-06-08'
last_week_end = today - timedelta(days=today.weekday()+1)
# datetime.date(2020, 6, 14)
# last_week_end.weekday() = 6
datetime — Basic date and time types
Example of how to GZIP compress an existing file:
import gzip
import shutil
with open('/home/joe/file.txt', 'rb') as f_in:
with gzip.open('/home/joe/file.txt.gz', 'wb') as f_out:
shutil.copyfileobj(f_in, f_out)
import os.path
# 检测文件是否存在:
os.path.isfile(fname)
if my_file.is_dir():
# 指定的目录存在
# 如果要检测路径是一个文件或目录可以使用 exists() 方法:
if my_file.exists():
# 指定的文件或目录存在
$ python -c "import sqlalchemy; print(sqlalchemy.__version__)"
How to check version of python modules?
sort
: change original list
sorted
: keep original list and return sorted list
Python列表排序方法reverse、sort、sorted详解
b = a > 1? "Greater thant 1":"Less than or equal to 1"
解决Python3 控制台输出InsecureRequestWarning的问题
print set(a) & set(b) # 交集, 等价于set(a).intersection(set(b))
print set(a) | set(b) # 并集, 等价于set(a).union(set(b))
print set(a) - set(b) # 差集,在a中但不在b中的元素, 等价于set(a).difference(set(b))
print set(b) - set(a) # 差集,在b中但不在a中的元素, 等价于set(b).difference(set(a))
def safe_cast(val, to_type, default=None):
try:
return to_type(val)
except (ValueError, TypeError):
return default
safe_cast('tst', int) # will return None
safe_cast('tst', int, 0) # will return 0
cPickle.load(f)
to cPickle.load(f, encoding='bytes')
- 成功解决Python3版UnicodeDecodeError: ‘ascii‘ codec can‘t decode byte 0x90 in position 614: ordinal not in
net.SGD(training_data, 30, 10, 3.0, test_data=test_data)
to net.SGD(list(training_data), 30, 10, 3.0, test_data=list(test_data))
replace xrange
to range