转载: Python3 输入和输出
1. 输出格式美化
- 表达式语句
- print()
- 使用文件对象的write()方法
- str.format() 函数来格式化输出值
- repr(), str() 将输出转换成字符串
repr(): 产生一个解释器易读的表达形式
str(): 返回一个用户易读的表达形式
#repr() 可以转移特殊字符
hello = 'hello,runoob\n'
hellos = repr(hello)
print(hello)
print(hellos)
hello,runoob
'hello,runoob\n'
两种方式输出一个平方与立方的表:
for x in range(1,11):
print(repr(x).rjust(2), repr(x*x).rjust(3),end=' ')
print(repr(x*x*x).rjust(4))
for x in range(1,11):
print('{0:2d} {1:3d} {2:4d}'.format(x,x*x,x*x*x))
# {0:2d}前面为起始的数, 2d表示间距
1 1 1
2 4 8
3 9 27
4 16 64
5 25 125
6 36 216
7 49 343
8 64 512
9 81 729
10 100 1000
format()
print('{0} 和 {1}'.format('Google', 'Runoob'))
Google 和 Runoob
print('{1} 和 {0}'.format('Google', 'Runoob'))
Runoob 和 Google
import math
print('常量 PI 的值近似为:%5.3f。' % math.pi)
print('常量 PI 的值近似为:{0:.3f}。'.format(math.pi))
常量 PI 的值近似为:3.142。
常量 PI 的值近似为:3.142。
2. input()
- input()
str = input('please input:')
print('你输入的内容是:',str)
- open(file,mode)
- write()
# open(filename, mode)
# mode decices how to open the file: read-only,write....
'''
r---read-only
w---write
a---if the file exists, open it; if not, create and write
, the pointer point to the end
+---用于读写
b--- 以二进制的形式'''
f = open('InputOutput.txt','w')
f.write('Jimmy: Python is an excellent language!\nSyvia: Yes, it is really good!\n')
f.close()
3. 文件对象方法
- f.read()
- f.readline()
- f.readlines():
f = open('InputOutput.txt','r')
str = f.read() #f.read(size)
print(str)
f.close()
Jimmy: Python is an excellent language!
Syvia: Yes, it is really good!
f = open('InputOutput.txt','r')
str = f.readline()
print(str)
f.close()
Jimmy: Python is an excellent language!
f = open('InputOutput.txt','r')
str = f.readlines() #readlines
print(str)
f.close()
['Jimmy: Python is an excellent language!\n', 'Syvia: Yes, it is really good!\n']
- f.tell()返回文件对象当前所处的位置, 它是从文件开头开始算起的字节数。
- f.seek(offset, from_what)改变文件当前的位置
from_what 的值,from_what 值为默认为0,即文件开头,如果是 1 表示当前位置, 2 表示文件的结尾,例如:
seek(x,0) : 从起始位置即文件首行首字符开始移动 x 个字符
seek(x,1) : 表示从当前位置往后移动x个字符
seek(-x,2):表示从文件的结尾往前移动x个字符
- close()
- piclkle(): 实现了基本的数据序列和反序列化。
序列化操作将程序中运行的对象信息保存到文件中去,永久存储。
反序列化操作从文件中创建上一次程序保存的对象。
基本接口:
pickle.dump(obj,file,[,protocol])
import pickle
# 使用pickle模块将数据对象保存到文件
data1= {'a': [1,2.0,3,4+6j],
'b':('string',u'Unicode string'),
'c': None}
selfref_list = [1,2,3]
selfref_list.append(selfref_list)
output = open('data.pkl','wb')
# pickle dictionary using protocol(保存字典data1)
pickle.dump(data1,output)
# pickle the list using the highest protocol available
pickle.dump(selfref_list,output,-1)
output.close()
f = open('data.pkl','rb')
df = pickle.load(f)
print(df)
f.close()
{'a': [1, 2.0, 3, (4+6j)], 'b': ('string', 'Unicode string'), 'c': None}
import pprint, pickle
#使用pickle模块从文件中重构python对象
pkl_file = open('data.pkl', 'rb')
data1 = pickle.load(pkl_file)
pprint.pprint(data1)
data2 = pickle.load(pkl_file)
pprint.pprint(data2)
pkl_file.close()
{'a': [1, 2.0, 3, (4+6j)], 'b': ('string', 'Unicode string'), 'c': None}
[1, 2, 3, <Recursion on list with id=2578464597576>]