Python Tutorial 学习(七)--Input and Output

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_..

时间: 2024-11-07 19:17:43

Python Tutorial 学习(七)--Input and Output的相关文章

转载:Pixhawk源码笔记四:学习RC Input and Output

转自:新浪@WalkAnt 第五部分 学习RC Input and Output 参考:http://dev.ardupilot.com/wiki/learning-ardupilot-rc-input-output/ RC Input,也就是遥控输入,用于控制飞行方向.改变飞行模式.控制摄像头等外围装置.ArduPilot支持集中不同RC input(取决于具体的硬件飞控板): 1. PPMSum – on PX4, Pixhawk, Linux and APM2 2. SBUS – on P

Python Tutorial 学习(六)--Modules

6. Modules 当你退出Python的shell模式然后又重新进入的时候,之前定义的变量,函数等都会没有了. 因此, 推荐的做法是将这些东西写入文件,并在适当的时候调用获取他们. 这就是为人所知的脚本文件. 随着编程的深入,代码的增多,你可能又会将代码存到不同的文件中方便管理. 你会想到去使用之前的编程中已经写好了的一个函数的定义. Python有自己的方式去实现这些.它会将这些保存了定义的函数,类等的文件(文件夹)称作module; 一个module中的定义的函数 类等可以被导入到另一个

Python Tutorial学习(十一)-- Brief Tour of the Standard Library – Part II

11.1. Output Formatting 格式化输出 The repr module provides a version of repr() customized for abbreviated displays of large or deeply nested containers: >>> import repr >>> repr.repr(set('supercalifragilisticexpialidocious')) "set(['a',

Python Tutorial 学习(四)--More Control Flow Tools

4.1 if 表达式 作为最为人熟知的if.你肯定对这样的一些表达式不感到陌生: >>> x = int(raw_input("Please enter an integer: ")) Please enter an integer: 42 >>> if x < 0: ... x = 0 ... print 'Negative changed to zero' ... elif x == 0: ... print 'Zero' ... elif

Python Tutorial 学习(五)--Data Structures

5. Data Structures 这一章来说说Python的数据结构 5.1. More on Lists 之前的文字里面简单的介绍了一些基本的东西,其中就涉及到了list的一点点的使用.当然,它可不仅仅只有那么一点点,这里给出一个更详细一点的说明.来吧骚连,打开你的命令行窗口 >>>help(list) 看看会出来一些什么~~` list.append(x) 向一个序列里面追加元素 x a = [] a.append(x) # 假设x已经定义了 a[len(a):] = [x] l

Python入门学习之input()与raw_input()的区别

登陆博客时才发现已经注册一年了,由于之前一直都没有打算从事软件开发行业,所以博客便被束之高阁,软件开发,对于我来说,是成长,更是磨炼.头脑风暴总是来去自由,记录灵感,与大家一起共享思维进步的成果. Python语言,很多人认为很简单,我也不否认,入门确实挺easy的,但是要达到精通,还是需要沉淀,积累.对于想学习Python的小伙伴来说,对于input()和raw_input()区别可能不是很清楚,也容易混淆,当然了,倘若你使用的是Python3.x版本,肯定就不用考虑什么input()与raw

Python Tutorial 学习(二)--Using the Python Interpreter

Using the Python Interpreter 2.1. Invoking the Interpreter The Python interpreter is usually installed as /usr/local/bin/python on those machines where it is available; putting /usr/local/bin in your Unix shell’s search path makes it possible to star

Python Tutorial 学习(三)--An Informal Introduction to Python

3.1. 将Python用作计算器 3.1.1. Numbers 数 作为一个计算器,python支持简单的操作, '+','-','*','/'地球人都知道的加减乘除. ()可以用来改变优先级,同数学里面的四则运算优先级一样. '='用来建立起表达式和变量间的联系,通俗点讲就是赋值. Afterwards, no result is displayed before the next interactive prompt (没看明白...) 变量在使用之前必须被定义. 浮点型的支持:用pyth

Python Tutorial 学习(一)--Whetting Your Appetite

Whetting Your Appetite [吊你的胃口]... 这里就直接原文奉上了... If you do much work on computers, eventually you find that there’s some task you’d like to automate. For example, you may wish to perform a search-and-replace over a large number of text files, or renam