[python]常识二


这里记录一下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(压缩和解压)的标准库

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值