7. Input and Output

Python里面有多种方式展示程序的输出.或是用便于人阅读的方式打印出来,或是存储到文件中以便将来使用....

本章将对这些方法予以讨论.

两种将其他类型的值转换为字符型值的方法:repr()和str(),二者的区别在于,一个是给机器读的,一个是给人读的,str()返回的是更适合人阅读的样式

一些栗子:

# coding=utf-8
# local_settings.py DEBUG = True DATABASE_NAME = 'missuor'
DATABASE_HOST = '127.0.0.1'
DATABASE_PORT = ''
DATABASE_USER = 'root'
DATABASE_PASS = ''
>>> 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_..

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

  1. Python Tutorial 学习(八)--Errors and Exceptions

    Python Tutorial 学习(八)--Errors and Exceptions恢复 Errors and Exceptions 错误与异常 此前,我们还没有开始着眼于错误信息.不过如果你是一 ...

  2. Python Tutorial 学习(六)--Modules

    6. Modules 当你退出Python的shell模式然后又重新进入的时候,之前定义的变量,函数等都会没有了. 因此, 推荐的做法是将这些东西写入文件,并在适当的时候调用获取他们. 这就是为人所知 ...

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

    11.1. Output Formatting 格式化输出 The repr module provides a version of repr() customized for abbreviate ...

  4. Python Tutorial 学习(五)--Data Structures

    5. Data Structures 这一章来说说Python的数据结构 5.1. More on Lists 之前的文字里面简单的介绍了一些基本的东西,其中就涉及到了list的一点点的使用.当然,它 ...

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

    4.1 if 表达式 作为最为人熟知的if.你肯定对这样的一些表达式不感到陌生: >>> x = int(raw_input("Please enter an intege ...

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

    Using the Python Interpreter 2.1. Invoking the Interpreter The Python interpreter is usually install ...

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

    登陆博客时才发现已经注册一年了,由于之前一直都没有打算从事软件开发行业,所以博客便被束之高阁,软件开发,对于我来说,是成长,更是磨炼.头脑风暴总是来去自由,记录灵感,与大家一起共享思维进步的成果. P ...

  8. Python Tutorial 学习(十)-- Brief Tour of the Standard Library

    10.1. Operating System Interface os库 import os os.getcwd() # Return the current working directory 'C ...

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

    3.1. 将Python用作计算器 3.1.1. Numbers 数 作为一个计算器,python支持简单的操作, '+','-','*','/'地球人都知道的加减乘除. ()可以用来改变优先级,同数 ...

随机推荐

  1. uvalive4513

    https://vjudge.net/problem/UVALive-4513 终于做出来了......... 各种sb错误,最后对拍出来了,还没改对..................... 快半天 ...

  2. SpringMVC 简单

    一.SpringMVC简介 SpringMVC也叫Spring Web mvc,属于表现层的框架.Spring MVC是Spring框架的一部分,是在Spring3.0后发布的 二.Spring结构图 ...

  3. 算法----希尔排序(shell sort)

    在分析插入排序(插入排序算法实现)的算法性能的过程时知道.当数组规模较小或者存在较多的有序子序列时.插入排序将会在非常短的时间内完毕数组的排序,为此能够设计一个单调序列h[n],将数组分为多个小的序列 ...

  4. 海思android4.4 SDK编译Latin输入法

    原来的HiSTBAndroidV500R001C01SPC020\device\hisilicon\bigfish\packages\apps\HiLatinIME\Android.mk内容例如以下: ...

  5. Qt 发送 https 请求

    1.环境 ubuntu 12.04 Qt库版本 4.8.1(安装包是Nokia时期的sdk,现在已经不好找了) 2.网上一查都说 Qt 默认不支持Openssl,心想那https也肯定用不了啊,然后屁 ...

  6. JAVA操作Excel时文字自适应单元格的宽度设置方法

    使用JAVA操作Excel通常都使用JXL,方法很简单网上也有很多的教程,然后往往一些细节性的问题却导致我们这些Programmer苦恼不已.这两天帮一个朋友做一个Excel表格自动生成的小软件,就遇 ...

  7. 高级性能调试手段(oprofile+gprofile)+内核追踪手段:LTT

    http://blog.csdn.net/wlsfling/article/details/5876134http://www.lenky.info/archives/2012/03/1371http ...

  8. 亲测PHP环境

    一.安装Apache2.2.22→1.下载软件,点安装 2.填写dengguoxing.com  www.dengguoxing.com(暂时不知道什么用)3.custom 个性化安装 更改路径即可 ...

  9. [转] Android LocalService与RemoteService理解

    前段时间被别人问到相关的问题,没有回答对,发现自己原来理解的有偏差,最近看了下,写了个小Demo实验了下,现在将其记录下来,以后千万别犯同样的错误就好了. 一.LocalService(本地服务) 不 ...

  10. Android 6.0 双卡拨号

    相关 api getCallCapablePhoneAccountsAdded in API level 23 Android 5.0 之前的版本 Call from second sim 获取 si ...