7.1. Fancier Output Formatting
两种方法,自己设置或者使用str.format()
还有对齐函数 str.rjust() method of string objects, which right-justifies a string in a field of a given width by paddingit with spaces on the left. There are similar methodsstr.ljust() andstr.center().str.zfill(), which pads a numeric string on theleft with zeros.
>>> '12'.zfill(5)
'00012'
>>> print 'We are the {} who say "{}!"'.format('knights', 'Ni')
We are the knights who say "Ni!"
A number in the brackets refers to the position of the object passed into thestr.format() method.
>>> 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.An optional ':' and format specifier can follow the field name. This allows greater control over how the value is formatted. The following examplerounds Pi to three places after the decimal.
>>> import math
>>> print 'The value of PI is approximately {0:.3f}.'.format(math.pi)
The value of PI is approximately 3.142.
7.1.1. Old string formatting
%模式,类似printf()函数>>> import math
>>> print 'The value of PI is approximately %5.3f.' % math.pi
The value of PI is approximately 3.142.
7.2. Reading and Writing Files
文件读写操作函数 open()、read()、readline()、write()、close()open()returns a file object, and is most commonly used with two arguments:open(filename, mode). 默认mode为r只读,可省略;w写,如果文件存在则先清空再重建,之前内容清空;r+为读写模式;a追加模式
>>> f = open('workfile', 'w')
>>> print f
<open file 'workfile', mode 'w' at 80a0960>
7.2.1. Methods of File Objects
To read a file’s contents, call f.read(size), which reads some quantity of data and returns it as a string. size is an optional numeric argument. When size is omitted or negative, the entire contents of the file will be read and returned; it’s your problem if the file is twice as large as your machine’smemory. Otherwise, at most size bytes are read and returned. If the end of the file has been reached, f.read() will return an empty string ( "").>>> f.read()
'This is the entire file.\n'
>>> f.read()
''
f.readline() reads a single line from the file; a newline character (
\n) is left at the end of the string
>>> f.readline()
'This is the first line of the file.\n'
>>> f.readline()
'Second line of the file\n'
>>> f.readline()
''
>>> 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'
When you’re done with a file, call
f.close() to close it and free up any system resources taken up by the open file. After calling
f.close(),a ttempts to use the file object will automatically fail.
>>> f.close()
>>> f.read()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: I/O operation on closed file