【python】创建,读取文件

通过指明打开的文件和模式来创建一个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/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值