文章目录
这里记录一下python 一些小技巧。
-1、时间格式化
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
0、获取当前时间戳
print(int(time.time() * 1000))
1、如何反转一个字符串
a3 = "abc"
print(a3[::-1]) # cba
a3[::-1]
这其实是对 a3 字符串取一个切片,但是步长为 -1 ,也就是从末尾读到头。
不得不说: python 语法真的特别简洁而富有表现力。
2、枚举和推导式生成列表
arr = ['a', 'b', 'c']
# 枚举 + 推导式生成列表
c = [str(index) + "#" + str(value) for index, value in enumerate(arr)]
# ['0#a', '1#b', '2#c']
print(c)
3、读取文件
with open('a.txt', 'r', encoding='utf-8') as f:
for line in f:
print(line.strip())
4、读取Excel csv
import openpyxl
wb=openpyxl.load_workbook(filename=r'test.xlsx')
sheet=wb['Sheet1']
for row in sheet.values:
# for value in row:
# print(value)
print(row[0])
import csv
with open('test.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
print(row[0])
# for value in row:
# print(value)
5、发起http 请求
payload = {
"name": "AAAAA"
}
headers = {
"content-type": "application/json",
# "Cookie": "AAAAA;"
}
with open('files\\2023_5_12.txt', 'r') as f:
lines = f.readlines()
for line in lines:
line = line.strip()
print('begin to do=>', line)
url = "http://AAAAA.com/api/"+line
response = requests.request("POST", url, json=payload, headers=headers)
print(response.text)
6、处理Json
demo = ['foo', {'bar': ('baz', None, 1.0, 2)}]
print(type(demo)) # <class 'list'>
# Serialize obj to a JSON formatted str.
dumped = json.dumps(demo)
print(type(dumped)) # str
# Deserialize obj from a JSON formatted str.
loaded = json.loads(dumped)
print(type(loaded)) # obj ,i.e.,list
foo = loaded[0][:1] # get the first character of 'foo'
print(foo) # str
7、序列化
pickle
,注意区分json序列化和序列化,pickle 类似java的 ObjectInputStream
a1 = 'hello world'
with open('a.txt','wb') as f:
pickle.dump(a1, f)
with open('a.txt','rb') as f:
print(pickle.load(f))
8、os模块(调取系统文件和函数)
os.system("notepad.exe") # 线程会阻塞在这里
print("hello world")
9、shutil(os 模块的补充,用于文件和目录的CRUD)
shutil.copyfile("a.txt", "aa.txt")
`
### 10、zipfile(压缩和解压)的标准库