Python: 深入Python的输入与输出
May 27, 2015
Table of Contents
1. 将任意值转化为字符串
s = "hello,world\n>"
>>> s1 = str(s) # 因为s原来为字符串,所以s只是保留了原样式
>>> s2 = repr(s) # repr保证了s的输出形式
>>> print(s1)
hello,world # s1 = 'hello,world\n'
>>> print(s2)
'hello,world\n' # s2 = "'hello,world\\n'>"
>>> x,y = 0,1
>>> list = [x,y,('ronny','young')]
>>> repr(list)
"[0,1,('ronny','young')]>"
2. 输出格式控制
如果字符串长超过了指定的宽度,则会原样输出,
>>> '-3.14'.zfill(7)
'-003.14'
str.format()的用法
>>> print('We are the {} who say "{}!>"'.format('knights', 'Ni')) # 基本用法
We are the knights who say "Ni!>"
>>> print('{1} and {0}'.format('spam', 'eggs')) #大括号内的数值指明传入str.fomat()方法的对象中的哪一个,前面的索引值小于后面给出参数的个数。
eggs and spam
如果在 str.format() 调用时使用关键字参数,可以通过参数名来引用值:
>>> print('This {food} is {adjective}.'.format(
... food='spam', adjective='absolutely horrible'))
This spam is absolutely horrible.
# 定位与关键字参数可以组合使用
>>> print('The story of {0}, {1}, and {other}.'.format('Bill', 'Manfred',
other='Georg'))
The story of Bill, Manfred, and Georg.
上面中format里的参数都是字符中,实际上也可以是其他类型,这时要进行转换
>>> import math
>>> print('The value of PI is approximately {}.'.format(math.pi))
The value of PI is approximately 3.14159265359.
>>> print('The value of PI is approximately {!r}.'.format(math.pi))
The value of PI is approximately 3.141592653589793.
字段名后允许可选的
# 控制浮点数显示的精度
>>> import math
>>> print('The value of PI is approximately {0:.3f}.'.format(math.pi))
The value of PI is approximately 3.142.
# 控制显示格式
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for name, phone in table.items():
... print('{0:10} ==> {1:10d}'.format(name, phone))
...
Jack ==> 4098
Dcab ==> 7678
Sjoerd ==> 4127
# 用命名来引用被格式化的变量
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {0[Jack]:d}; Sjoerd: {0[Sjoerd]:d}; '
'Dcab: {0[Dcab]:d}'.format(table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
# 也可以用 ‘**’ 标志将这个字典以关键字参数的方式传入
>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
>>> print('Jack: {Jack:d}; Sjoerd: {Sjoerd:d}; Dcab: {Dcab:d}'.format(**table))
Jack: 4098; Sjoerd: 4127; Dcab: 8637678
3. 文件的读写
3.1 打开文件
>>> f = open('~/python/somefile','w') #以写的方式打开文件
‘rb’ 以二进制方式打开文件,并且只读。
3.2 从文件中读取字符串
f.read(size) # 从打开的f中读取若干数量的数据并以字符串形式返回其内容,size为字符串长度。如果没有指定size或为负数,则返回整个文件。
执行
f.readline() # 读取一行,字符串结束有换行符。文件结尾时 没有换行符。 f.readlines() # 返回一个列表,包含了文件中所有的数据行。
一种替代的方法是通过遍历文件对象来读取文件行。这是一种内存高效,快速,并且代码简洁的方法:
for line in f:
printf(line, end=' ') #防止换二行
>>> value = ('the answer', 42)
>>> s = str(value)
>>> f.write(s)
18
3.3 流的定位
需要改变文件指针的话,使用
用关键字
with open('~/work/python/file', 'r') as f:
... read_data = f.read()
>>> f.closed
True
0 Comments