通过指明打开的文件和模式来创建一个file类的实例。模式可以为读模式('r')、写模式('w')或追加模式('a')。
用写模式打开文件,然后使用file类的write方法来写文件,最后用close关闭这个文件。再一次打开同一个文件来读文件。如果程序中没有指定模式,读模式会作为默认的模式。在一个循环中,使用readline方法读文件的每一行。这个方法返回包括行末换行符的一个完整行。所以,当一个 空的 字符串被返回的时候,即表示文件末已经到达了,于是我们停止循环。
注意,因为从文件读到的内容已经以换行符结尾,在print语句上使用逗号来消除自动换行。
下面的例子使用了 file, open两种方式来读取文件,注意两者的不同。
#!/etc/bin/python
#!-*- coding:utf8 -*-
# Filename using_file.py
content ='''\
this is a test file,using file class to make a new file with this text
yangql is a boy ,like oracle ,although there is lots of things there for me to
learn .I think it is a good chance to be a excellent DBA '''
filename= 'yangql-DBA.txt'
fileobj = file(filename,'w')--以写的方式创建一个文件
fileobj.write(content)--向文件中写入内容
fileobj.close()
f = file(filename) --以file()的方式打开刚才创建的文件,默认是读。
print '-----------------make file yangql-DBA.TXT successfully!!--------------'
print '-----------------the follow text comes from yangql-DBA.txt-------------'
print ' '
while True:
line = f.readline()
if len(line) ==0:
break
print line,
f.close()
print ' '
print '----------------the follow text comes from open class func------------'
fobj = open(filename,'r')
for eachline in fobj:
print eachline,
fobj.close()
"using_file.py" 36L, 853C written
[yang@rac1 python]$ python using_file.py
-----------------make file yangql-DBA.TXT successfully!!--------------
-----------------the follow text comes from yangql-DBA.txt-------------
this is a test file,using file class to make a new file with this text
yangql is a boy ,like oracle ,although there is lots of things there for me to
learn .I think it is a good chance to be a excellent DBA
----------------the follow text comes from open class func------------
this is a test file,using file class to make a new file with this text
yangql is a boy ,like oracle ,although there is lots of things there for me to
learn .I think it is a good chance to be a excellent DBA
[yang@rac1 python]$
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/22664653/viewspace-702692/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/22664653/viewspace-702692/