python:文件读写

读文件

要以读文件的模式打开一个文件对象,使用Python内置的open()函数,传入文件名和标示符:

>>> f = open('/Users/michael/test.txt', 'r')

标示符'r'表示读,这样,我们就成功地打开了一个文件。

如果文件不存在,open()函数就会抛出一个IOError的错误,并且给出错误码和详细的信息告诉你文件不存在:

>>> f=open('/Users/michael/notfound.txt', 'r')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '/Users/michael/notfound.txt'
如果文件打开成功,接下来,调用 read()方法可以一次读取文件的全部内容,Python把内容读到内存,用一个 str对象表示:

>>> f.read()
'Hello, world!'
最后一步是调用 close()方法关闭文件。

>>> f.close()
对于IOError的异常,为了保证无论是否出错都能正确地关闭文件,我们可以使用 try ... finally来实现:

try:
    f = open('/path/to/file', 'r')
    print(f.read())
finally:
    if f:
        f.close()
但是每次都这么写实在太繁琐,所以,Python引入了 with语句来自动帮我们调用 close()方法:

with open('/path/to/file', 'r') as f:
    print(f.read())
这和前面的 try ... finally是一样的,但是代码更佳简洁,并且不必调用 f.close()方法。

写文件

写文件和读文件是一样的,唯一区别是调用open()函数时,传入标识符'w'或者'wb'表示写文本文件或写二进制文件:

>>> f = open('/Users/michael/test.txt', 'w')
>>> f.write('Hello, world!')
>>> f.close()
也可以用with语句

with open('/Users/michael/test.txt', 'w') as f:
    f.write('Hello, world!')
在Python中,文件读写是通过 open()函数打开的文件对象完成的。使用 with语句操作文件IO是个好习惯。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# with_file.py

from datetime import datetime

with open('test.txt', 'w') as f:
	f.write('今天是 ')
	f.write(datetime.now().strftime('%Y-%m-%d'))

with open('test.txt', 'r') as f:
	s = f.read()
	print('open for read...')
	print(s)

with open('test.txt', 'rb') as f:
	s = f.read()
	print('open as binary for read...')
	print(s)
结果为:

open for read...
今天是 2017-03-22
open as binary for read...
b'\xbd\xf1\xcc\xec\xca\xc7 2017-03-22'

原文出处:http://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431917715991ef1ebc19d15a4afdace1169a464eecc2000








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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值