原文地址:http://blog.csdn.net/ztf312/article/details/47259805
第一步 排除文件打开方式错误:
r只读,r+读写,不创建
w新建只写,w+新建读写,二者都会将文件内容清零
(以w方式打开,不能读出。w+可读写)
**w+与r+区别:
r+:可读可写,若文件不存在,报错;w+: 可读可写,若文件不存在,创建
r+与a+区别:
fd = open("1.txt",\'w+\') fd.write(\'123\') fd = open("1.txt",\'r+\') fd.write(\'456\') fd = open("1.txt",\'a+\') fd.write(\'789\')
结果:456789
说明r+进行了覆盖写。
以a,a+的方式打开文件,附加方式打开
(a:附加写方式打开,不可读;a+: 附加读写方式打开)
以 \'U\' 标志打开文件, 所有的行分割符通过 Python 的输入方法(例#如 read*() ),返回时都会被替换为换行符\n. (\'rU\' 模式也支持 \'rb\' 选项) .
r和U要求文件必须存在
不可读的打开方式:w和a
若不存在会创建新文件的打开方式:a,a+,w,w+
>>> fd=open(r\'f:\mypython\test.py\',\'w\') #只读方式打开,读取报错 >>> fd.read() Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: File not open for reading >>> fd=open(r\'f:\mypython\test.py\',\'a\')#附加写方式打开,读取报错 >>> fd.read() Traceback (most recent call last): File "<stdin>", line 1, in <module> IOError: File not open for reading >>></span></span></span>