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的运用
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,288评论 19 139
  • linux资料总章2.1 1.0写的不好抱歉 但是2.0已经改了很多 但是错误还是无法避免 以后资料会慢慢更新 大...
    数据革命阅读 12,270评论 2 33
  • 5.1 读写文本数据 你需要读写各种不同编码的文本数据,比如ASCII,UTF-8或UTF-16编码等。 使用带有...
    czm123阅读 382评论 0 1
  • 1、通过CocoaPods安装项目名称项目信息 AFNetworking网络请求组件 FMDB本地数据库组件 SD...
    阳明AI阅读 16,033评论 3 119
  • 文/西红十八 【写在前面半废不废的话】 世界杯期间也应个景儿,我这个业余十八线伪球迷也来说说足球,少林足球。 毕竟...
    西红十八阅读 606评论 0 0