打开一个文件并向其写入内容
testFile = open(' cainiao.txt',' w')
#error testFile.write(u'菜鸟写Python!')
#写入一个字符串
testFile. write('菜鸟写Python!')
#字符串元组
codeStr = ('<div>','<p>','完全没有必要啊!','
')
Python的open方法用来打开一个文件。第一个参数是文件的位置和文件名,第二个参数是读写模式。这里我们采用w模式,也就是写模式。在这种模式下,文件原有的内容将会被删除。
#to writetestFile = open(' cainiao.txt',' w')
#error testFile.write(u'菜鸟写Python!')
#写入一个字符串
testFile. write('菜鸟写Python!')
#字符串元组
codeStr = ('<div>','<p>','完全没有必要啊!','
','
testFile.write('\n\n')
#将字符串元组按行写入文件
testFile. writelines (codeStr)
#关闭文件。
testFile. close ()向文件添加内容
在open的时候制定'a'即为(append)模式,在这种模式下,文件的原有内容不会消失,新写入的内容会自动被添加到文件的末尾。
#to appendtestFile = open('cainiao.txt',' a ')
testFile.write('\n\n')
testFile.close()读文件内容
在open的时候制定'r'即为读取模式,使用
#to readtestFile = open('cainiao.txt','r')
testStr = testFile. readline ()
print testStr
testStr = testFile. read ()
print testStr
testFile.close()在文件中存储和恢复Python对象
使用Python的pickle模块,可以将Python对象直接存储在文件中,并且可以再以后需要的时候重新恢复到内容中。
testFile = open('pickle.txt','w')#and import pickle
import pickle
testDict = {'name':'Chen