本文共 2079 字,大约阅读时间需要 6 分钟。
f = open("hello.txt", "r") # 打开文件进行读取content = f.read(10) # 读取10个字节的内容content = f.readline() # 读取一行内容content = f.readlines() # 读取所有行内容
f.write("I like apple\r\n") # 写入文件,注意换行符依赖于操作系统f.close() # 手动关闭文件
with
语句可以自动管理资源的生命周期。文件操作中,使用上下文管理器可以避免手动关闭文件,代码更加简洁。 with open("file.txt", "w") as f:f.write("Hello World!")print(f.closed) # 输出True,表示文件已关闭
import pickleclass Bird(object):have_feather = Truereproduction_method = "egg"
保存对象
with open("bird.pkl", "wb") as f:pickle.dump(summer, f)
加载对象
with open("bird.pkl", "rb") as f:summer = pickle.load(f)print(summer.have_feather) # 输出True
import datetime获取当前时间
now = datetime.datetime.now()print(now) # 输出当前时间
测量程序运行时间
start = datetime.datetime(2012, 9, 3, 21, 30)for _ in range(100000):passend = datetime.datetime(2012, 9, 3, 21, 30)print(end - start) # 输出2秒
时间间隔运算
delta = datetime.timedelta(days=2)end_date = start + deltaprint(end_date - start) # 输出2天
日期格式转换
date_str = "2012-09-05-00-00-00"date = datetime.datetime.strptime(date_str, "%Y-%m-%d-%H-%M-%S")print(date.strftime("%Y-%m-%d %H:%M")) # 输出2012-09-05 00:00:00
import re搜索模式
pattern = r"[0-9]"match = re.search(pattern, "abcd4ef56")print(match.group(0)) # 输出4print(match.group()) # 输出4
替换操作
replace_pattern = re.sub("[0-9]", "love", "abcd4ef56")print(replace_pattern) # 输出abcdloveflove
分割操作
split_pattern = re.split("[0-9]", "abcd4ef56")print(split_pattern) # 输出['abcd', 'ef', '', '']
查找所有匹配
findall_pattern = re.findall("[0-9]", "abcd4ef56")print(findall_pattern) # 输出['4', '5', '6']
import http.clientconn = http.client.HTTPConnection("www.example.com")conn.request("GET", "/")response = conn.getresponse()print(response.status, response.reason) # 输出200 OK
读取响应内容
content = response.read()print(content)
转载地址:http://fzzp.baihongyu.com/