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中文文件读写脚本
- python Ini文件读写
- Python文件的读写
- python对文件进行读写操作
- python文件读写
- Python读写Unicode文件
- Python对unicode文件的读写和使用正则表达式
- python读写UCS-2 big/little endian(utf-16-be/utf-16-le)格式的文件
- [Python]读写文件方法
- python基础5--文件操作--字符串读写
- Python字符集编码和文件读写
- Python读写文件
- Python读写文件
- Python学习笔记--文件读写
- Python读写文件
- Python open读写文件实现脚本
- Python open读写文件实现脚本
- Python天天美味(17) - open读写文件
- 使用Python进行二进制文件读写
- python基础6--文件操作--对象的读写