迭代器和生成器
- 文本迭代器
with open("001.txt", "r", encoding="utf8", errors="ignore") as f:
print(f)
try:
while True:
print(next(f))
except Exception:
pass
with open("001.txt", "r", encoding="utf8", errors="ignore") as f:
for line in f:
print(line)
- 代理迭代
class People:
def __init__(self):
self._name = "人"
self._age = "小于200岁"
self._list = [1, 2, 3, 4, 5]
def __repr__(self):
return "名%s活多久%s" % (self._name, self._age)
def __iter__(self):
return iter(self._list)
p = People()
print(str(p))
print(list(iter(p)))
- io数据操作
import io
s = io.StringIO()
s.write("hellol")
s.write("aaaaa")
print(s.getvalue())
- 文件压缩gzip,bz2
import gzip
with open("id.txt", "r") as f:
text = f.read()
with gzip.open("id.gz", "wt") as file:
file.write(text)
import os
length = os.path.getsize("id.gz")
print(length)
- 获取相关文件目录
import glob
g = glob.glob("*.txt")
print(g)
name_sz_date = [(name, os.path.getsize(name), os.path.getmtime(name))
for name in pyfiles]
for name, size, mtime in name_sz_date:
print(name, size, mtime)
- pickle,json的运用
网友评论