Python - 输入输出(六)
你想要从用户那里获取输入然后将一些结果打印。我们可以分别使用input() 和print() 函数来实现。
对于输入,我们也可以使用str(string) 类的各种方法。例如,你能够使用rjust 方法来得到一个按一定宽度右对齐的字符串。
用户输入
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")
给一个负的步长,如-1 会将文本逆转。
input() 函数用一个字符串作为其参数,然后显示给用户。然后等待用户键入一些东西,按返回键。一旦用户键入,input() 函数就返回该文本。
文件
你可以通过创建一个file 类的对象来打开一个文件,分别使用file 类的read、readline 或write 方法来恰当地读写文件。对文件的读写能力依赖于你在打开文件时指定的模式。最后,当你完成对文件的操作的时候,你调用close 方法来告诉Python 我们完成了对文件的使用。
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
首先,我们通过指明我们希望打开的文件和模式来创建一个file 类的实例。模式可以为读模式(’r’)、写模式(’w’)或追加模式(’a’)。事实上还有多得多的模式可以使用,你可以使用help(file) 来了解它们的详情。默认情况下,open() 认为文件是text 文件,且用read 模式打开。
pickle 模块
Python 提供了一个叫做pickle 的标准模块,使用该模块你可以将任意对象存储在文件中,之后你又可以将其完整地取出来。这被称为持久地存储对象。
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 # detroy the shoplist variable
# Read back from the storage
f = open(shoplistfile,'rb')
storedlist = pickle.load(f) # load the object from the file
print(storedlist)
为了在文件里储存一个对象,首先以写,二进制模式打开一个file 对象,然后调用pickle 模块的dump 函数,这个过程称为pickling 。
接下来,我们用pickle 模块的返回对象的load 函数重新取回对象。这个过程称之为unpickling 。