python读写文件操作_Python文件操作读写文件

最基本的文件操作当然就是在文件中读写数据。这也是很容易掌握的。现在打开一个文件以进行写操作:

1. fileHandle = open ( 'test.txt', 'w' )

fileHandle = open ( 'test.txt', 'w' )

„w'

是指文件将被写入数据,语句的其它部分很好理解。下一步就是将数据写入文件:

1. fileHandle.write ( 'This is a test.\nReally, it is.' )

fileHandle.write ( 'This is a test.\nReally, it is.' )

这个语句将

“This is a test.”

写入文件的第一行,

“Really, it is.”

写入文件的第二行。最后,我们需要做清理工

作,并且关闭文件:

1. fileHandle.close()

fileHandle.close()

正如你所见,在

Python

的面向对象机制下,这确实非常简单。需要注意的是,当你再次使用

“w”

方式在文

件中写数据,所有原来的内容都会被删除。如果想保留原来的内容,可以使用

“a”

方式在文件中结尾附加数

据:

1. fileHandle = open ( 'test.txt', 'a' )

2. fileHandle.write ( '\n\nBottom line.' )

3. fileHandle.close()

fileHandle = open ( 'test.txt', 'a' )

fileHandle.write ( '\n\nBottom line.' )

fileHandle.close()

然后,我们读取

test.txt

,并将内容显示出来:

1. fileHandle = open ( 'test.txt' )

2. print fileHandle.read()

3. fileHandle.close()

fileHandle = open ( 'test.txt' )

print fileHandle.read()

fileHandle.close()

以上语句将读取整个文件并显示其中的数据。我们也可以读取文件中的一行:

1. fileHandle = open ( 'test.txt' )

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值