您的位置:首页 > 编程语言 > Python开发

python:文件读写

2017-03-22 15:02 183 查看

读文件

要以读文件的模式打开一个文件对象,使用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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python