Python笔记(9)

Python中的文件操作以及输入输出

我们可以分别使用raw_inputprint语句来完成这些功能。对于输出,你也可以使用多种多样的str(字符串)类。例如,你能够使用rjust方法来得到一个按一定宽度右对齐的字符串。利用help(str)获得更多详情。

 

 

另一个常用的输入/输出类型是处理文件。创建、读和写文件的能力是许多程序所必需的,我们将会在这章探索如何实现这些功能。

 

一.使用文件

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

 

#!/usr/bin/python # Filename: using_file.py poem = '''/ Programming is fun When the work is done if you wanna make your work also fun: use Python! ''' f = file('poem.txt', 'w') # open for 'w'riting f.write(poem) # write text to file f.close() # close the file f = file('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, # Notice comma to avoid automatic newline added by Python f.close() # close the file

 

输出为:

$ python using_file.py Programming is fun When the work is done if you wanna make your work also fun: use Python!

模式可以为读模式('r')、写模式('w')或追加模式('a')。详细情况可见help(file)

 

二.存储器

Python提供一个标准的模块,称为pickle。使用它你可以在一个文件中储存任何Python对象,之后你又可以把它完整无缺地取出来。这被称为持久地储存对象。

 

还有另一个模块称为cPickle,它的功能和pickle模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle快1000倍)。你可以使用它们中的任一个,而我们在这里将使用cPickle模块。记住,我们把这两个模块都简称为pickle模块。

 

例如:

#!/usr/bin/python # Filename: pickling.py import cPickle as p #import pickle as p shoplistfile = 'shoplist.data' # the name of the file where we will store the object shoplist = ['apple', 'mango', 'carrot'] # Write to the file f = file(shoplistfile, 'w') p.dump(shoplist, f) # dump the object to a file f.close() del shoplist # remove the shoplist # Read back from the storage f = file(shoplistfile) storedlist = p.load(f) print storedlist

 

输出为:

 

$ python pickling.py ['apple', 'mango', 'carrot']

 

你可能感兴趣的:(apple,python,object,File,fun,newline)