7. Input and Output
Python里面有多种方式展示程序的输出.或是用便于人阅读的方式打印出来,或是存储到文件中以便将来使用....
本章将对这些方法予以讨论.
两种将其他类型的值转换为字符型值的方法:repr()和str(),二者的区别在于,一个是给机器读的,一个是给人读的,str()返回的是更适合人阅读的样式
一些栗子:
>>> s = ‘Hello, world.‘ >>> str(s) ‘Hello, world.‘ >>> repr(s) "‘Hello, world.‘" >>> str(1.0/7.0) ‘0.142857142857‘ >>> repr(1.0/7.0) ‘0.14285714285714285‘ >>> x = 10 * 3.25 >>> y = 200 * 200 >>> s = ‘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... >>> # The repr() of a string adds string quotes and backslashes: ... hello = ‘hello, world\n‘ >>> hellos = repr(hello) >>> print hellos ‘hello, world\n‘ >>> # The argument to repr() may be any Python object: ... repr((x, y, (‘spam‘, ‘eggs‘))) "(32.5, 40000, (‘spam‘, ‘eggs‘))" 再举两个以表格格式输出平方和立方的栗子:
>>> for x in range(1, 5): ... print repr(x).rjust(2), repr(x*x).rjust(3), ... # Note trailing comma on previous line ... print repr(x*x*x).rjust(4) ... 1 1 1 2 4 8 3 9 27 4 16 64 >>> for x in range(1,5): ... 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
(Note that in the first example, one space between each column was added by the way print works: it always adds spaces between its arguments.)
字符串的一些方法:
str.rjust() 右对齐
str.ljust() 左对齐
str.center() 居中
注:当字符串长度大于指定的长度时,将直接返回原始长度的字符串(可以用str.ljust(n)[n:]切片的方式截取定长字符串)
str还有一个方法就是str.zfill()这个会将左边的不足的位补上字符0,还有一点需要赞一个的是,它能明白正号和负号哟,举个栗子:
>>> ‘12‘.zfill(5) ‘00012‘ >>> ‘-3.14‘.zfill(7) ‘-003.14‘ >>> ‘3.14159265359‘.zfill(5) ‘3.14159265359‘
下面介绍的一个是str.formt()
>>> print ‘We are the {} who say "{}!"‘.format(‘knights‘, ‘Ni‘) We are the knights who say "Ni!"
还可以这样:
>>> print ‘{0} and {1}‘.format(‘spam‘, ‘eggs‘) spam and eggs >>> print ‘{1} and {0}‘.format(‘spam‘, ‘eggs‘) eggs and spam
还可以这样:
>>> 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.
‘!s‘ (apply str()) and ‘!r‘ (apply repr()) can be used to convert the value before it is formatted.
>>> 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.
‘:‘可以指定更多的格式,看起来有点像C语言里面的哎呀:
比如,下面的栗子里面我们只需要保留小数点后3位数:
>>> 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
This is particularly useful in combination with the built-in function vars(), which returns a dictionary containing all local variables.
For a complete overview of string formatting with str.format(), see Format String Syntax.
7.1.1. Old string formatting 旧版本的字符串格式化方法:
The % operator can also be used for string formatting. It interprets the left argument much like a sprintf()-style format string to be applied to the right argument, and returns the string resulting from this formatting operation. For example:
>>> import math >>> print ‘The value of PI is approximately %5.3f.‘ % math.pi The value of PI is approximately 3.142.
More information can be found in the String Formatting Operations section.
7.2. Reading and Writing Files 文件读写
open() 返回一个文件对象, 通常给两个参数(文件和读写模式): open(filename, mode).
>>> f = open(‘workfile‘, ‘w‘) >>> print f <open file ‘workfile‘, mode ‘w‘ at 80a0960>
第一个参数是包含文件名的字符串(完整路径或者是相对路径)
第二个参数的文件的读写模式,通常会是 r 只读, w 只写, a 追加,r+ 读写, 缺省状态下是只读.当前面的一个模式加上一个‘b‘的时候,表示的是以二进制的方式进行操作.(注意,在Windows下面,带‘b‘的模式,有时候,可能会出幺蛾子哟)
7.2.1. Methods of File Objects 文件对象的一些方法
下面的一些栗子里面将会直接用 f 表示一个已经创建的文件对象.
f.read(size) 将会读取指定长度的文件内容并以字符串的形式返回.size 是一个可选参数,当其为空或者是负值的时候,整个文件的内容将会被返回.
当文件过大(超过内存的两倍)的时候,出问题的时候, 可不要找Python的麻烦(机器限制).否则,在机器条件允许的情况下,文件的读操作会返回尽可能多的数据.已经读到文件的尾部再去读的时候,会返回一个空字符串("").就像下面这个栗子.
>>> f.read() ‘This is the entire file.\n‘ >>> f.read() ‘‘
f.readline() 每次读取一行,不多也不少.行的结尾是一个 ‘\n‘,当然,如果一个文件只有一行,那结尾肯定也是一个‘\n‘,哎呀,好糊涂,简单说就是每行的结尾必然会有一个换行的标志,这让Python的f.readline() 的返回变得更加的 ‘不那么模糊‘.给个栗子帮助更好的理解:
>>> f.readline() ‘This is the first line of the file.\n‘ >>> f.readline() ‘Second line of the file\n‘ >>> f.readline() ‘‘
遍历一个文件对象将会是这样的:
>>> for line in f: print line, This is the first line of the file. Second line of the file 新技能get~
又如果你想一次性读取所有的行,list(f)或者 f.readlines()可以帮到你.
f.write(string) 会将字符串的内容写入文件,这个操作返回的是None(不返回).
>>> f.write(‘This is a test\n‘)
f.write()接收字符串作为参数,这意味着,非字符串的对象往文件写入的时候,必须进行类型转换,比如,这样:
>>> value = (‘the answer‘, 42) >>> s = str(value) >>> f.write(s)
f.tell() 返回当前文件对象所处的位置,就像是指针(C语言里面很熟悉吧),字节是基本单位哟.
f.seek(offset, from_what) 用来指定‘指针‘的位置.offset是相对于from_whar的偏移.from_what 是个整数,表示当前的字节位置.
给个栗子:
>>> f = open(‘workfile‘, ‘r+‘) >>> f.write(‘0123456789abcdef‘) >>> f.seek(5) # Go to the 6th byte in the file >>> f.read(1) ‘5‘ >>> f.seek(-3, 2) # Go to the 3rd byte before the end >>> f.read(1) ‘d‘
f.close() 用来关闭已经操作完毕的文件对象并且释放由于对文件操作而占用是系统资源,该操作结束过后,在去使用 f 就会引发一个错误(已经不存在了).
>>> f.close() >>> f.read() Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: I/O operation on closed file
使用关键字 with 来对待文件对象是很不错的.它会在文件操作结束过后自动帮你把文件对象关闭,即使是在操作过程中引发了错误...这可比try except短得多哟.
>>> with open(‘workfile‘, ‘r‘) as f: ... read_data = f.read() >>> f.closed True
File objects have some additional methods, such as isatty() and truncate() which are less frequently used; consult the Library Reference for a complete guide to file objects.
7.2.2. Saving structured data with json 用json来存储数据结构
由于read() 操作只返回字符串,从文件中读出或写入字符串是很容易的一件事,而换成整形的数字则会多费一点手脚(需要多用int()函数来来一发).
When you want to save more complex data types like nested lists and dictionaries, parsing and serializing by hand becomes complicated.
Rather than having users constantly writing and debugging code to save complicated data types to files, Python allows you to use the popular data interchange format called JSON (JavaScript Object Notation). The standard module called json can take Python data hierarchies, and convert them to string representations; this process is called serializing. Reconstructing the data from the string representation is called deserializing. Between serializing and deserializing, the string representing the object may have been stored in a file or data, or sent over a network connection to some distant machine.
Note
The JSON format is commonly used by modern applications to allow for data exchange. Many programmers are already familiar with it, which makes it a good choice for interoperability.
If you have an object x, you can view its JSON string representation with a simple line of code:
>>> json.dumps([1, ‘simple‘, ‘list‘]) ‘[1, "simple", "list"]‘
Another variant of the dumps() function, called dump(), simply serializes the object to a file. So if f is a file object opened for writing, we can do this:
json.dump(x, f)
To decode the object again, if f is a file object which has been opened for reading:
x = json.load(f)
This simple serialization technique can handle lists and dictionaries, but serializing arbitrary class instances in JSON requires a bit of extra effort. The reference for the json module contains an explanation of this.
See also
pickle - the pickle module
Contrary to JSON, pickle is a protocol which allows the serialization of arbitrarily complex Python objects. As such, it is specific to Python and cannot be used to communicate with applications written in other languages. It is also insecure by default: deserializing pickle data coming from an untrusted source can execute arbitrary code, if the data was crafted by a skilled attacker.
睡觉,玩手机去,就是这么任性,懒得往下看了.__orz_..