Python入门系列:Input/Output

[size=medium]引言[/size]
在一些场景中,你的程序需要与用户交互。例如你想接收用户的输入并打印一些结果作为反馈。我们已经分别通过input()和print()函数实现了这个过程。
在输出窗口,有时我们需要看到str(string)类的各种方法。例如你可以使用rjust方法获得一个指定宽度的右对齐的字符串,更多细节通过help(str)获得。
input/output另外一个常用的方式是对文件的操作。对于很多程序来说,创建、读取和写回文件是不可或缺的部分,下面的部分将向你展示这些应用。

[size=large][b]Input from user[/b][/size]
# 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")

[size=medium]输出结果:[/size]
$ python user_input.py
Enter text: sir
No, it is not a palindrome
$ python user_input.py
Enter text: madam
Yes, it is a palindrome
$ python user_input.py
Enter text: racecar
Yes, it is a palindrome

[size=medium]执行过程:[/size]
我们使用slicing方式对字符串进行反转,在sequence部分,我们已经看到了如何通过使用seq[a:b]的方式进行slice操作来获得从a到b位置之间的元素。同时我们提供第三个参数用指定slice操作的步长。默认的步长是1用来返回原文本中的一段连续的内容。程序中我们指定步长为-1,从而获得了文本的反转形式(即实现文本的前后倒置)。
input()函数使用了一个字符串参数来提供用户输入,然后开始等待用户输入内容,并按下回车键,而input()函数就会返回用户刚刚输入的内容。我们接收用户输入的文本内容,并对之进行了反转。如果原文本与反转后的文本相同,那些原文本就是回文的(palindrome,正向和反向读取的内容相同)。

[b][size=large]Files[/size][/b]
你可以通过创建file对象来打开和使用文件,用于读取或写入内容,也可以使用合适的read, readline和write方法来对文件进行读取或者写入内容。最后,当你对文件操作完成后,你需要使用close方法告诉Python我们对文件使用已经结束。
下面的代码演示了file的简单用法:
# 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

[size=medium]输出结果:[/size]
$ python using_file.py
Programming is fun
When the work is done
if you wanna make your work also fun:
use Python!

[size=medium]执行过程:[/size]
首先通过python内置的open函数打开文件,使用该方法时需要为其指定文件名称和打开的模式。python提供的可选的模式有:读('r'),写('w')和追加(append)('a')。同时我们也可以指定处理的文件是文本文件('t')或者二进制文件('b'),例open('poem.txt', 'wt')将以写模式打开名称为'poem.txt'的文本文件。事实上还有更多的模式使用,详细信息可以通过help(open)来获得。open()默认以读('r')模式以文本形式('t')打开文件。
在上面的例子中,我们首先以写文本模式打开文件,然后使用file对象的write方法对文件进行写入,然后使用close关闭文件。
然后我们以读模式再次打开文件。因为“读文本”模式是open的默认模式,所以我们不需要指定模式。我们在循环中通过readline依次读入每一行内容。readline方法会返回一个完整的行,其中包括该行末尾用来标示新行的字符。当返回的字符串为空(len(f.readline())==0)时,这就意思着我们已经到达了文件的末尾,从而跳出了循环。
默认情况下,print()函数会对输出的每一行结束后进行换行。我们可以通过指定end=' '使print不进行换行,因为从文件中读出的每一行中包含了一个换行符。最后我们关闭文件。
现在,你可以查看poem.txt文件的内容,确信程序的确对该文件进行了写操作和读操作。

[b][size=large]Pickle[/size][/b]
Python标准模块库中提供了一个用来存储把任何python对象存储到文件中,然后再恢复成python对象的模块,这个模块叫做pickle。我们把这种对对象的存储称为持久化(persistently)。
下面的代码演示了pickle的简单使用:
# 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)

[size=medium]输出结果:[/size]
$ python pickling.py
['apple', 'mango', 'carrot']

[size=medium]执行过程:[/size]
为了把对象保存到文件中,我们首先以"写二进制('wb')"的模式打开一个文件,然后调用pickle模块中的dump方法,我们称这个过程为pickling。然后我们通过执行pickle模块的load函数从文件中加载对象,我们称这个过程为unpickling。

说明:该文章从 A byte of Python v1.92 for Python3.0翻译而来,望指正
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值