1、文件
可以通过创建一个file
类的对象来打开一个文件,分别使用file
类的read
、readline
或write
方法来恰当地读写文件。对文件的读写能力依赖于打开文件时指定的模式。最后,完成对文件的操作的时候,调用close
方法来告诉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'
),事实上还有多得多的模式可以使用。再一次打开同一个文件来读文件,如果没有指定模式,读模式会作为默认的模式。在一个循环中,使用readline
方法读文件的每一行,这个方法返回包括行末换行符的一个完整行。所以,当一个 空的 字符串被返回的时候,即表示文件末已经到达了,于是停止循环。
注意,因为从文件读到的内容已经以换行符结尾,所以在print
语句上使用逗号来消除自动换行。最后,用close
关闭这个件。
Python提供一个标准的模块,称为pickle
。使用它可以在一个文件中储存任何Python对象,之后又可以把它完整无缺地取出来。这被称为 持久地 储存对象。
还有另一个模块称为cPickle
,它的功能和pickle
模块完全相同,只不过它是用C语言编写的,因此要快得多(比pickle
快1000倍),可以使用它们中的任一个。记住,把这两个模块都简称为pickle
模块。
# 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']
使用了import..as
语法:这是一种便利方法,以便于可以使用更短的模块名称。在这个例子中,它使得能够通过简单地改变一行就切换到另一个模块(cPickle
或者pickle
)!在程序的其余部分的时候,简单地把这个模块称为p
。
为了在文件里储存一个对象,首先以写模式打开一个file
对象,然后调用储存器模块的dump
函数,把对象储存到打开的文件中。这个过程称为 储存 。接下来,使用pickle
模块的load
函数的返回来取回对象。这个过程称为 取储存 。