python读取文件
有了fobject对象,我们就可以获取文件所有的内容
>>> fobject.read() 'onitroad is awesome!\n'
如果以读取模式打开文件,但去尝试写操作,将会引发“IO.UNSupportedOperation”异常:
>>> fobject.write('onitroad is awesome!') Traceback (most recent call last): File "<stdin>", line 1, in <module> io.UnsupportedOperation: not writable
关闭文件对象
在对文件操作完成后,始终记得关闭文件。
with open('onitroad.txt', 'r') as fileobject: content = fileobject.read() # perform needed operations
打开文件
Python Open函数打开一个文件并返回一个file对象,如果文件无法访问,则会抛出OSError异常。
>>> fobject = open('onitroad.txt')
默认的打开方式是读取文本文件,即上面的命令等同于:
>>> fobject = open('onitroad.txt', 'rt')
如果文件不存在,则会抛出FileNotFoundError异常:
>>> fobject = open('onitroad.txt') Traceback (most recent call last): File "<stdin>", line 1, in <module> FileNotFoundError: [Errno 2] No such file or directory: 'onitroad.txt'
python写入文件
使用write方法将字符串文本写入文件中。
写入时使用w写入模式:
>>> fobject = open('onitroad.txt', 'w') >>> fobject.write('We just wrote to the file!') 26 >>> fobject.close()
在只写模式中,尝试读取操作将会报错:not readable
>>> fobject = open('onitroad.txt', 'w') >>> fobject.read() Traceback (most recent call last): File "", line 1, in io.UnsupportedOperation: not readable
追加模式
要想将文本追加到文件末尾,使用a模式:
>>> fobject = open('onitroad.txt', 'a') >>> fobject.write('Appended text!') 14 >>> fobject.close()
'x'模式
此模式仅在Python3中可用。
如果文件已存在,则会引发一个fileexistserror
。
如果文件不存在,则会创建和打开新文件:
fileobject = open('onitroad.txt', 'x') Traceback (most recent call last): File "<stdin>", line 1, in <module> FileExistsError: [Errno 17] File exists: 'onitroad.txt'
日期:2020-07-07 20:54:28 来源:oir作者:oir