菜鸟学python(7) 简单文件访问

想写点东西把自己学习python的过程记录下来,于是就有了菜鸟学python

首先是使用open来读取事先准备好的一个文本文件:1.txt

文件中的东西很简单:

<span style="font-family:Arial;">successful!!!
this file is ok!
why not do best?</span>

将这个文本文件放入和我们要执行的代码同一目录下

下面的代码可以将txt中的文件输出。运行后输入1.txt

<span style="font-family:Arial;font-size:12px;">filename = raw_input('Enter file name:')
fileobj = open(filename,'r')
for eachline in fileobj:
    print eachline,
fileobj.close()</span>

1.txt中的文字就可以输出到屏幕上


下面通过open我们将字符写入到文件中

这里我们通过w模式将打开文件,写入字符,关闭文件,再输出文件

<pre name="code" class="python" style="line-height: 26px;"><span style="font-size: 12px;"></span><pre name="code" class="python"><pre name="code" class="python" style="line-height: 26px;"><span style="font-family:Arial;">filename = raw_input('Enter file name:')</span>

 
<span style="font-family: Arial;">fileobj = open(filename,'w')</span>
 
<span style="font-family: Arial;">fileobj.write("writing in this txt file!")</span>
<span style="font-family: Arial;">fileobj.close()</span>
<span style="font-family: Arial;">print fobj.readline()</span>
 

运行后发现程序报错

来看一下异常抛出

<span style="font-family:Arial;">try:
    filename = raw_input('Enter file name:')
    fileobj = open(filename,'w')
    fileobj.write("writing in this txt file!")
    print fileobj.readline()
except IOError,e:
    print 'file error is :',e</span>

运行结果file error is : File not open for reading

这是因为在使用w模式之后不能直接使用readline将文件打开
如果直接使用readline语句则会报错IOError: File not open for reading

这时我们将文件关闭后再通过r模式打开,就可以将我们之前写好的语句显示在屏幕上了

<span style="font-family:Arial;font-size:12px;">fileobj = open(filename,'r')
print fileobj.readline()</span>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值