标签:文件io
一、打开和关闭文件
1、文件打开和关闭
In [1]: help(open)
Help on built-in function open in module io:
open(file, mode=‘r‘, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
    Open file and return a stream.  Raise IOError upon failure.
    
    ========= ===============================================================
    Character Meaning
    --------- ---------------------------------------------------------------
    ‘r‘       open for reading (default)
    ‘w‘       open for writing, truncating the file first
    ‘x‘       create a new file and open it for writing
    ‘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 (deprecated)
    ========= ===============================================================     
    
In [6]: f = open("/tmp/shell/test.txt")  # 打开一个文件,获得一个文件对象
In [7]: type(f)
Out[7]: _io.TextIOWrapper
In [8]: f
Out[8]: <_io.TextIOWrapper name=‘/tmp/shell/test.txt‘ mode=‘r‘ encoding=‘UTF-8‘>
In [9]: f.mode  # 文件对象的打开模式
Out[9]: ‘r‘
In [11]: f.name  # 文件名 
Out[11]: ‘/tmp/shell/test.txt‘
In [13]: f.read()  # 读取文件的内容
Out[13]: ‘Hello World!\nI love python\n‘
In [15]: f.readable()  # 是否可读
Out[15]: True
In [16]: f.writable()  # 是否可写
Out[16]: False
In [17]: f.closed  # 文件对象是否关闭
Out[17]: False
In [20]: f.close()  # 关闭文件对象
In [21]: f.name
Out[21]: ‘/tmp/shell/test.txt‘
In [22]: f.read()  # 关闭后不能再查看了
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-22-bacd0e0f09a3> in <module>()
----> 1 f.read()
ValueError: I/O operation on closed file.
In [25]: f.closed
Out[25]: True  文件对象的操作和打开方式是相关
2、open函数mode参数详解
控制读写的模式:
 ‘r‘ :即mode=r,默认,只读打开,不可写;当文件不存在时,会抛出FileNotFoundError     
 ‘w‘:只写打开,不可读;会清空原文件,当文件不存在时,会新建
 ‘x‘ :仅新建文件,只写打开,不可读;当文件存在时,会抛出FileExistError    
 ‘a‘ :追加内容到文件末尾(最后一行的下面一行),只写,不可读;当文件不存在时,会新建
从读写的方面来看,只有r可读不可写,其它都是可写不可读
当文件不存在时,只有r抛出异常,其它的都创建新文件
当文件存在时,只有x抛出异常
从是否影响文件原始内容来看,只有w会清空文件
‘b‘ :以二进制的方式打开,     
 ‘t‘      
 ‘+‘       
 ‘U‘ 
标签:文件io
原文地址:http://xiexiaojun.blog.51cto.com/2305291/1944844