格式化输出
两种表达式和print()函数,第三种是使用文件对象的write()方法
使用repr()或者str()函数可以将值转为字符串
str()返回一个用户已读的表达式;repr()返回一个解析器已读的表达式
>>> x='hello world'
>>> str(x)
'hello world'
>>> x
'hello world'
>>> repr(x)
"'hello world'"
>>> print(x)
hello world
>>> str(1/3)
'0.3333333333333333'
>>> repr(1/3)
'0.3333333333333333'
>>>
>>> x=10*1.23
>>> y=3*100
>>> a = 'x value :' + repr(x)+', y value is :'+repr(y)
>>> a
'x value :12.3, y value is :300'
>>> print(a)
x value :12.3, y value is :300
#输出平方立方例子
>>> for x in range(1, 9):
... print(repr(x).rjust(2),repr(x*x).rjust(3),end=' ')
... print(repr(x*x*x).rjust(4))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
>>> for x in range(1,9):
... print('{0:2d} {2:3d} {2:4d}'.format(x,x*x,x*x*x))
...
1 1 1
2 8 8
3 27 27
4 64 64
5 125 125
6 216 216
7 343 343
8 512 512
>>> for x in range(1,9):
... print('{0:2d} {1:3d} {2:4d}'.format(x,x*x,x*x*x))
...
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
第一个例子中,每列间的空格有print()补充;并且展示了rjust()函数,他可以将字符串靠右,并在左侧使用空格填充;
类似的方法,ljust()和center(),这些方法并不会写任何,仅仅返回新的字符串;
相对应,有一个方法zfill(),将在数字左边填充0
>>> n=123
>>> n.zfill(5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'int' object has no attribute 'zfill'
>>> str(n).zfill(5)
'00123'
>>> str(n).zfill(1)
'123'
str.format()基本使用
>>> print('{}ello {}orld!'.format('h','w'))
hello world!
括号里的字符(格式化字段)将会被format(0中的参数替换;在括号中指定使用数字用于指向转入对象在format()中的位置
>>> print('{1},{0}'.format('world','hello'))
hello,world
>>> print('{name1},{name2}'.format(name2='world',name1='hello'))
hello,world
可选项‘:'和格式标识符可以跟着字段名,进而对数值格式化
>>> import math
>>> print('PI value is {0:3f}'.format(math.pi))
PI value is 3.141593
>>> print('PI value is {0:.3f}'.format(math.pi))
PI value is 3.142
格式化宽度
>>> t={'China': 1,'USA':2}
>>> for name,number in t.items():
... print('{0:5} ==> {1:20d}'.format(name,number))
...
USA ==> 2
China ==> 1
%操作符可以实现字符串格式化,不推荐使用,将来可能被移除,使用str.format()
>>> import math
>>> print('pi value is: %10.5f' %math.pi)
pi value is: 3.14159
>>> print('pi value is: %5.5f' %math.pi)
pi value is: 3.14159
>>> print('pi value is: %8.5f' %math.pi)
pi value is: 3.14159
读取键盘输入
使用input()内置函数从标准输入读取一行文本,默认标准输入键盘;input可以接受一个表达式,并将运算结果返回
>>> s=input("please input:")
please input:hello world
>>> print(s)
hello world
读写文件
open()将会返回一个file对象,语法
open(filename,mode)
其中,filename是一个包含将要访问文件名称的字符串;mode是打开文件的模式,只读,写入,追加等,可以不指定,默认值是只读
模式 | 描述 |
r | 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。 |
rb | 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。 |
r+ | 打开一个文件用于读写。文件指针将会放在文件的开头。 |
rb+ | 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。 |
w | 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
wb | 以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
w+ | 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
wb+ | 以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。 |
a | 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 |
ab | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。 |
a+ | 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。 |
ab+ | 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。 |
例子
>>> f = open("/tmp/1.txt","w")
>>> f.write('hello world')
11
>>> f.close
<built-in method close of _io.TextIOWrapper object at 0x7f67667d2c18>
>>> f.close()
其中11为写入的字符数
结果
[root@centos7 ~]# cat /tmp/1.txt
hello world[root@centos7 ~]#
文件对象方法
读取文件内容
f.read()
使用f.read()读取文件内容,其中f.read(size)用于读取一定数目的数据,如果size忽略,那么该文教案的所有内容将被读取
文件内容
[root@centos7 ~]# cat /tmp/1.txt
hello world
123
读取实例:
>>> f = open("/tmp/1.txt","r")
>>> s=f.read(5)
>>> print(s)
hello
>>> s=f.read(11)
>>> print(s)
world
123
>>> s=f.read()
>>> print(s)
f.readline()
读取单独一行,换行符为‘\n',返回空串说明到了最后一行
>>> f = open("/tmp/1.txt","r")
>>> s=f.readline()
>>> print(s)
hello world
>>> s=f.readline()
>>> print(s)
123
>>> s=f.readline()
>>> print(s)
>>> f.close()
f.readlines()
返回该文件的所有行,可以加入size选项
>>> f = open("/tmp/1.txt","r")
>>> s=f.readlines()
>>> print(s)
['hello world\n', '123\n']
迭代读取文件每一行
>>> f = open("/tmp/1.txt","r")
>>> for line in f:
... print(line,end='')
...
hello world
123
>>> f.close()
f.write()
f.write(str)将str写入到文件,然后返回写入的字符数
>>> f = open("/tmp/1.txt","w")
>>> num=f.write('hello world')
>>> print(num)
11
>>> f.close()
写入非字符串要进行转换
>>> f = open("/tmp/1.txt","w")
>>> x=123
>>> f.write(x)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: write() argument must be str, not int
>>> f.write(str(x))
3
>>> f.close()
f.tell()
返回文件对象当前所处的位置,从文件开头开始算起的字节数
f.seek()
如果要改变文件按当前的位置,可以使用f.seek(offset,from_pos)函数
其中from_pos如果是0表示开头,1表示当前位置,2表示文件结尾
seek(x,0):从起始位置移动x个字符
seek(x,1):从当前位置后移x歌字符
seek(-x,2):从文件的结尾前移x个字符
>>> f = open("/tmp/1.txt","w+")
>>> f.write('123456')
6
>>> s=f.read(1)
>>> print(s)
>>> f.seek(-1,2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
io.UnsupportedOperation: can't do nonzero end-relative seeks
>>> f.seek(-1,1)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
io.UnsupportedOperation: can't do nonzero cur-relative seeks
>>> f.seek(1,0)
1
>>> s=f.read(1)
>>> print(s)
2
>>> f.seek(1,0)
1
>>> s=f.read(1)
>>> print(s)
2
f.close()
处理完需要关闭文件,释放系统资源
pickle模块
pickle模块实现了基本的数据序列和反序列化
通过pickle模块的序列化操作,能够将程序中运行的对象信息永久保存到文件中;
通过pickle模块的反序列化,能够从文件中创建上一次程序保存的对象
pickle.dump(obj,file,[,protocol])
可以使用pickle的对file以读取模式打开
x=pickle.load(file) -- 从file中读取一个字符串,并将它重构为原来的python对象
例子
>>> import pickle
>>> d1={'a':123,'b':456}
>>> list1=[1,2,3]
>>> list1.append(list1)
>>> list1
[1, 2, 3, [...]]
>>> print(list1)
[1, 2, 3, [...]]
>>> list1.append(list1)
>>> print(list1)
[1, 2, 3, [...], [...]]
>>> f=open('1.txt','wb')
>>> pickle.dump(d1,f)
>>> pickle.dump(list1,f,-1)
>>> f.close
<built-in method close of _io.BufferedWriter object at 0x7f48db632258>
>>> f.close()
>>>
>>> import pprint,pickle
>>> pfile=open('11.txt','rb')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '11.txt'
>>> pfile=open('1.txt','rb')
>>> d1=pickle.load(pfile)
>>> pprint.pprint(d1)
{'a': 123, 'b': 456}
>>> d2=pickle.load(pfile)
>>> pprint.pprint(d2)
[1,
2,
3,
<Recursion on list with id=139950892519048>,
<Recursion on list with id=139950892519048>]
>>> pfile.close()
附:
文件方法
file对象常用方法
方法 | 描述 |
file.close() | 关闭文件。关闭后文件不能再进行读写操作。 |
file.flush() | 刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。 |
file.fileno() | 返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。 |
file.isatty() | 如果文件连接到一个终端设备返回 True,否则返回 False。 |
file.next() | 返回文件下一行。 |
file.read([size]) | 从文件读取指定的字节数,如果未给定或为负则读取所有。 |
file.readline([size]) | 读取整行,包括 "\n" 字符。 |
file.readlines([sizeint]) | 读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。 |
file.seek(offset[, whence]) | 设置文件当前位置 |
file.tell() | 返回文件当前位置。 |
file.truncate([size]) | 截取文件,截取的字节通过size指定,默认为当前文件位置。 |
file.write(str) | 将字符串写入文件,没有返回值。 |
file.writelines(sequence) | 向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。 |