Python学习总结(6)-IO

来源:互联网 发布:淘宝网上怎样申请退款 编辑:程序博客网 时间:2024/04/30 09:42

格式化输出

# 基本用法print 'We are the {} who say "{}!"'.format('knights', 'Ni')# 指定位置print '{1} and {0}'.format('spam', 'eggs')# output : eggs and spam# 使用关键字参数print 'This {food} is {adjective}.'.format(food='spam', adjective='absolutely horrible')# 关键字参数和位置参数混合使用print 'The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred', other='Georg')# !s(str())和!r(repr()),被格式化之前,调用对应的函数进行转换print 'The value of PI is approximately {!r}.'.format(math.pi)# 关键字参数和位置参数之后可加 ":"和格式指令# 将Pi转为三位精度print 'The value of PI is approximately {0:.3f}.'.format(math.pi)# : 后跟整数可以限制该字段的最小宽度print '{0:10} ==> {1:10d}'.format(name, phone)# 格式化字典table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}print ('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; Dcab: {0[Dcab]:d}'.format(table))# 或者使用 **print 'Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table)

读写文件

# 打开,并返回文件对象# w:写入,r:读取,a:追加,rb,wb,r+b:二进制形式读写f = open("filename", "w")# 读取整个文件f.read()# 读取指定大小f.read(size)# 读取一行数据f.readline()# 遍历循环读取文件中的每一行for line in f:    print line# 将所有行读取列表中list(f) # 或 f.readlines()# 将string内容写入文件,并返回Nonef.write(string)# 文件对象在文件中的指针位置 f.tell() # 设置指针位置# from_what:0,以文件开始作为参考点# 1 当前文件位置作为参考点# 2 文件的结尾作为参考点f.seek(offset, from_what)# 关闭文件f.close()# 文件是否关闭, 返回布尔类型f.closed()# 类似Java中的try-resource,自动释放文件with open("filename", "r") as f:    read_data = f.read()
0 0
原创粉丝点击