Python的open方法用来打开一个文件。第一个参数是文件的位置和文件名,第二个参数是读写模式;
f=open('/1.txt','w')
读写模式的类型有:
rU 或 Ua 以读方式打开, 同时提供通用换行符支持 (PEP 278)
w
a
r+
w+
a+
rb
wb
ab
rb+
wb+
ab+
a.
注意:1、使用'W',文件若存在,首先要清空,然后(重新)创建,
3、使用'a'模式 ,把所有要写入文件的数据都追加到文件的末尾,即使你使用了seek()指向文件的其他地方,如果文件不存在,将自动被创建。
3、使用open打开文件后一定要记得关闭文件对象,f.close()。可以用try/finally语句来确保最后能关闭文件。
![Python <wbr>open读写文件 Python <wbr>open读写文件](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![Python <wbr>open读写文件 Python <wbr>open读写文件](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![Python <wbr>open读写文件 Python <wbr>open读写文件](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![Python <wbr>open读写文件 Python <wbr>open读写文件](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
![Python <wbr>open读写文件 Python <wbr>open读写文件](https://i-blog.csdnimg.cn/blog_migrate/f0cd6c7f9e7ae96feae062cb48f670f0.gif)
注:不能把open语句放在try块里,因为当打开文件出现异常时,文件对象file_object无法执行close()方法。