【Python】 Python输入和输出
来源:互联网 发布:c专家编程亚马逊 编辑:程序博客网 时间:2024/05/24 05:02
输出格式美化
Python两种输出值得方式:表达式语句和print()函数(第三种方式是使用文件对象的write()方法 标准输出文件可以用sys.stdout引用)
如果你希望输出对的形式更加多样,可以使用str.format()函数来格式化输出值
如果你希望将输出的值转成字符串,可以使用repr()或str()函数来实现。
str()函数返回一个用户易读的表达形式。
repr()产生一个解释器易读的表达形式。
如
s = 'Hello,world.'str(s)>>>'Hello,world.'repr(s)>>>"'Hello,world.'"str(1/7)>>>'0.14285714285714285'x = 10*3.25y = 200*200s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'print(s)The value of x is 32.5, and y is 40000...hello = 'hello,world\n'hellos = repr(hello)print(hellos)>>>'hello,world'
输出平方 立方表
#rjust()方法可以将字符串靠右,并在左边填充空格。for i in range(1,11): 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 9 81 72910 100 1000for x in range(1,11): 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 9 81 72910 100 1000
str.format()用法:
{}及里面的字符会被format()中的参数替换。在括号中的数字用于指向传入对象在format()中的位置
如
>>> print('{0} and {1}'.format('spam', 'eggs'))spam and eggs>>> print('{1} and {0}'.format('spam', 'eggs'))eggs and spam
如果在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.
‘!a’ (使用 ascii()), ‘!s’ (使用 str()) 和 ‘!r’ (使用 repr()) 可以用于在格式化某个值之前对其进行转化:
>>> 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.
可选项”:”和格式标识符可以跟着字段名。这就允许对值进行更好的格式化。下面的例子将Pi保留到小数点后三位:
import mathprint('{0:3f}'.format(math.pi))>>>3.142
在’:’后传入一个整数,可以保证该域至少有这么多的宽度,用于美化表格时很有用。
如果你有一个很长的格式化字符串, 而你不想将它们分开, 那么在格式化时通过变量名而非位置会是很好的事情。
最简单的就是传入一个字典, 然后使用方括号 ‘[]’ 来访问键值 :
>>> 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 变量前使用 ‘**’ 来实现相同的功能:
>>> 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
旧式字符串格式化
>>> import math>>> print('The value of PI is approximately %5.3f.' % math.pi)The value of PI is approximately 3.142.
读和写文件
open()将会返回一个file对象,基本语法格式如下
open(filename,mode)
如
f = open(‘/tmp/workfile’,’w’)
第一个参数使要打开的文件名
第二个参数描述文件如何使用的字符。mode可以使’r’如果文件只读。’w’只用于写(如果存在同名文件则将被删除)。’a’用于追加文件内容。所写的任何数据都会被自动增加到末尾.’r+’同时用于读写.
mode参数是可选的,’r’是默认值
文件对象的方法
f.read()
为了读取一个文件的内容,调用f.read(size).
将读取一定数目的数据,然后作为字符串或字节对象返回.
size是一个可选的数字类型的参数.当size被忽略或者为负,那么该文件的所有内容都将被读取并且返回.
f.read()>>>'This is the entire file.\n'
f.readline()
读取单独一行.如果返回空字符串说明已经读到最后一行
>>> f.readline()'This is the first line of the file.\n'>>> f.readline()'Second line of the file\n'>>> f.readline()''
f.readlines()
返回该文件中所有的行
>>> f.readlines()['This is the first line of the file.\n', 'Second line of the file\n']
另一种方式是迭代一个文件对象然后读取每行:
>>> for line in f:... print(line, end='')...This is the first line of the file.Second line of the file
这个方法很简单, 但是并没有提供一个很好的控制。 因为两者的处理机制不同, 最好不要混用。
f.write()
f.write(string)将string写入到文件中,然后返回写入的字符数
f.write('This is a test\n')>>>15
如果写入的不是字符串,需要先转换
>>> value = ('the answer', 42)>>> s = str(value)>>> f.write(s)18
f.close()
在处理完一个文件后,调用f.close()来关闭文件并释放系统的资源,如果尝试再调用该文件,则会抛出异常
也可以使用with语句.结束后会帮助你正确的关闭文件,写起来也比try finally简短
with open('/tmp/workfile','r') as f: read_data = f.read()f.closed>>>True
pickle 模块
python的pickle模块实现了基本的数据序列和反序列化。
通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储.
通过pickle模块的反序列化操作我们能够从文件中创建上一次程序保存的对象.
基本接口:
pickle.dump(obj,file,[,protocol])
有了pickle这个对象,就能对file以读取的形式打开:
x = pickle.load(file)#从file中读取一个字符串,并将它重构为原来的python对象
file:类文件对象,有read()和readline()接口
实例1:
#使用pickle模块将数据对象保存到文件import pickledata1 = {'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.pk1','wb')pickle.dump(data1,output)pickle.dump(selfref_list,output,-1)output.close()
实例2:
import pprint,picklepkl_file = open('data.pk1','rb')data1 = pickle.load(pk1_file)pprint.pprint(data1)data2 = pickle.load(pk1_file)pprint.pprint(data2)pkl_file.close()
- 【Python】 Python输入和输出
- python 输入和输出
- python输入和输出
- Python输入和输出
- Python 输入和输出
- Python输入和输出
- python的输入和输出
- python 指南 输入和输出
- Python学习 - 输入和输出
- python文件输入和输出
- python 文件输入和输出
- python 3 输入和输出
- Python的输入和输出
- [python基础] 输入和输出
- python处理输入和输出
- Python中输入和输出
- Python-文件输入和输出
- Python开发-Python文件处理-Python文件输入和输出
- 1043. Is It a Binary Search Tree (25)
- IOS中SQLite3使用
- CodeForces 238C World Eater Brothers 树形dp
- Android 高仿微信头像截取 打造不一样的自定义控件
- iphone 6 plus 人気 とまだ、このサイト特にベッドが片側にこのキー事実小さな印刷装置を設定する事に
- 【Python】 Python输入和输出
- mosquitto1.4 websocket js客户端测试
- MVC中的Html.ActionLink的介绍
- Android-->将布局文件放在服务器上,动态改变布局。
- Robtinum
- c++STL中优先队列的使用
- unity3d 研究之 性能优化
- アイフォン6 ケース 手帳 ボーダフォンPAYGでケンモアのViewty Ku990iによるクラスとスタイル
- git使用方法和常用命令