转 Python学习(十)

原文出处


作者:Wanglikai91 
出处:http://www.cnblogs.com/wanglikai91/ 

十、输入/输出

一些情况下你不得不让程序与用户进行交互。例如,你需要从用户处得到输入然后输出计算结果。我们可以分别通过input()和print()函数做到这些。 
对于输出,我们还可以使用str(string)类的各种方法。例如rjust方法可以得到一个指定宽度的右对齐字符串。详见help(str)。 
另一种常见的输入/输出类型为文件处理。创建、读和写文件的能力是许多程序所必需的,我们将会在这章探索如何实现这些功能。

1、用户输入

1
2
3
4
5
6
7
8
9
10
11
12
13
# user_input.py
  
def reverse(text):
    return text[::-1]
  
def is_palindrome(text):
    return text == reverse(text)
  
something = input('Enter text: ')
if (is_palindrome(something)):
    print("Yes, it is a palindrome")
else:
    print("No, it is not a palindrome")

输出:

C:\Users\Administrator>python D:\python\user_input.py 
Enter text: sir 
No, it is not a palindrome C:\Users\Administrator>python D:\python\user_input.py 
Enter text: racecar 
Yes, it is a palindrome

工作原理:

例中我们使用切片操作反转文本。之前我们已经学过如何通过seq[a:b](从a开始止于b)对序列切片。 
对于切片操作我们还可以指定第三个参数步长,步长默认为1将返回文本的一个连续部分。而给定一个负步长-1将返回反转后的文本。 
input()函数接收一个字符串实参并将其打印给用户,然后函数等待用户输入一些东西,一但用户按下回车键则输入结束,input函数将返回输入的文本。 
之后我们反转文本,如果反转后的文本与原文本相同,则代表它是一个回文。

2、文件

你可以通过创建一个file类的对象来打开一个文件,分别使用file类的read、readline或write方法来恰当地读写文件。对文件的读写能力依赖于你在打开文件时指定的模式。最后,当你完成对文件的操作的时候,你调用close方法来告诉Python我们完成了对文件的使用。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Filename: using_file.py
  
poem = '''\
Programming is fun
When the work is done
if you wanna make your work also fun:
    use Python!
'''
  
f = open('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
  
f = open('poem.txt') # if no mode is specified, 'r'ead mode is assumed by default
while True:
    line = f.readline()
    if len(line) == 0: # Zero length indicates EOF
        break
    print(line, end='')
f.close() # close the file

输出:

C:\Users\Administrator>python D:\python\using_file.py 
Programming is fun 
When the work is done 
if you wanna make your work also fun: 
    use Python!

工作原理:

首先,我们通过内建函数open打开一个文件,在函数中我们指定了被打开文件的文件名与希望使用的打开模式。其中打开模式可以为读模式(‘r’),写模式(‘w’)或追加模式(‘a’)。另外我们也可以处理文件文件(‘t’)和二进制文件(‘b’)。实际上还有很多模式可用,详见help(open)。默认的open将文件对待为文本文件’t’,并以读模式’r’打开。 
在范例中,我们首先以写文本模式打开文件,使用文件对象的write方法写文件,并调用close将其关闭。然后我们再次打开相同的文件用于读取。这里我们无需指定打开模式因为’读文本文件’是open的默认模式。 
在循环中我们使用readline方法读取文件的每一行。这个方法返回一整行文本其中包括末尾的换行符。当返回一个空字符串时,意味着我们已经来到文件尾,因此使用break跳出循环。 
默认的,print()函数将自动打印一个换行。因为从文件读出的文本行末尾已经包含一个换行,所以我们指定参数end=’’抑制换行。 
最后我们关闭文件。 
现在,检查poem.txt文件内容以确定程序真的写入并读取了文件。

3、储存器(pickle)

python提供了一个名为pickle的标准模块用于将任意python对象存入文件或从文件中读出。这被称做永久性存储对象(persistently)。

例如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# Filename: pickling.py
  
import pickle
  
# the name of the file where we will store the object
shoplistfile = 'shoplist.data'
# the list of things to buy
shoplist = ['apple', 'mango', 'carrot']
  
# Write to the file
f = open(shoplistfile, 'wb')
pickle.dump(shoplist, f) # dump the object to a file
f.close()
  
del shoplist # destroy the shoplist variable
  
# Read back from the storage
f = open(shoplistfile, 'rb')
storedlist = pickle.load(f) # load the object from the file
print(storedlist)

输入:

C:\Users\Administrator>python D:\python\pickling.py 
['apple', 'mango', 'carrot']

工作原理:

为了将对象存储到文件,我们必须首先’wb’写二进制文件模式打开文件然后调用pickle模块的dump函数。这个过程叫做封藏(pickling)对象。 
接下来我们使用pickle的load函数重新找回对象。这个过程叫做解封(unpickling)对象。

 

posted @ 2016-12-02 23:50  凯心宝牙  阅读(172)  评论(0编辑  收藏  举报