python cookbook学习笔记04

迭代器和生成器

  1. 文本迭代器
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)
  1. 代理迭代
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)))
  1. io数据操作
import io
s = io.StringIO()
s.write("hellol")
s.write("aaaaa")
print(s.getvalue())
  1. 文件压缩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)

  1. 获取相关文件目录
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)
  1. pickle,json的运用

你可能感兴趣的:(python cookbook学习笔记04)