打开文件会用到open函数,标准的python打开文件语法如下:
open(name[,mode[,buffering]])
open函数的文件名是必须的,而模式和缓冲参数都是可选的。比如说有个a.txt的文本文件,存放在/Users/bingweizhang/Desktop下,那么你要打开它可以这样操作:
open('/Users/bingweizhang/Desktop/a.txt','r')
用读的模式打开这个路径下的对应文本文件,如果要打开对像不存在,程序会报错。
*IOError: [Errno 2] No such file or directory: '/Users/bingweizhang/Desktop/b.txt'*
二、open()函数文件打开模式参数常用值有哪些?
刚才打开文件过程中用到了‘r’这个参数,在文件打开过程中还会用到很多操作方法,都有不同的参数来表示。'r'读模式、'w'写模式、'a'追加模式、'b'二进制模式、'+'读/写模式。
Character Meaning
‘r' open for reading (default)
‘w' open for writing, truncating the file first
‘a' open for writing, appending to the end of the file if it exists
‘b' binary mode
‘t' text mode (default)
‘+' open a disk file for updating (reading and writing)
‘U' universal newline mode (for backwards compatibility; should not be used in new