Python_文件操做

文件操做

一、文件路徑:  如 d:\ '文件名稱‘.後綴python

二、編碼方式: utf-8  gbk ......app

三、操做方式: 只讀,只寫,追加,讀寫,寫讀......less

 以什麼編碼方式存儲的文件,就以什麼編碼打開進行操做。ide

具體表現:

只讀: rui

絕對路徑
f = open('e:\\a1.py', mode='r', encoding='utf-8') content = f.read() print(content) f.close()

相對路徑
f = open('xxx', mode='r', encoding='utf-8')
content = f.read()
f.close()
 

註釋:絕對路徑打開,須要 open(‘文件在硬盤中的地址+後綴’,mode=‘r’,encoding=‘utf-8’),若是路徑是 a1 這樣簡短的文件名,須要另外加一個 \ 不影響正常讀取並且分割區分 this

           \a 在python中的關鍵字。
            相對路徑  只須要文件在同一個目錄下,而且文件名稱正確,經過正確的格式就能打開。編碼

只讀: rb            bytes類型   系統內部 傳輸 存儲 使用。spa

f = open('e:\\t1.py', mode='rb')
content = f.read()
print(content)
f.close()

不須要設定編碼方式,‘rb’已經內部默認
讀寫: r+  只能先讀後寫,而且不能續寫,只能完成一步讀寫,不能是讀寫讀寫讀寫。3d

f = open('e:\\t2.py', mode='r+', encoding='utf-8')
content = f.read()
contents = f.write('a11')
print(content,contents)
f.close()

只寫 : ‘w’  沒有此文件就會建立文件,已經有的,刪除原文件,再寫入新文件指針

f = open('e:\\t2.py', mode='w', encoding='utf-8')
content = f.write('asdadas')
print(content)
f.close()

寫讀: w+ 寫讀   先所有刪除,而後寫入

f = open('e:\\t2.py', mode='w+', encoding='utf-8')
f.write('a11')
f.seek(0)
print(f.read())
f.close()

x, 只寫模式【不可讀;不存在則建立,存在則報錯】

f = open('e:\\t6.py', mode='x', encoding='utf-8')
f.write('a11aa')
f.close()

a, 追加模式【可讀;   不存在則建立;存在則只追加內容;】

f = open('e:\\t2.py', mode='a', encoding='utf-8')
f.write('1qqw')
print(f)
f.close()

a+, 寫讀【可讀,可寫】

f = open('e:\\t2.py', mode='a+', encoding='utf-8')
f.write('陽展')
print(f.read())
f.close()

 "b"表示以字節的方式操做

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b

 注:以b方式打開時,讀取到的內容是字節類型,寫入時也須要提供字節類型

class file(object)
    def close(self): # real signature unknown; restored from __doc__
        關閉文件
        """
        close() -> None or (perhaps) an integer.  Close the file.
         
        Sets data attribute .closed to True.  A closed file cannot be used for
        further I/O operations.  close() may be called more than once without
        error.  Some kinds of file objects (for example, opened by popen())
        may return an exit status upon closing.
        """
 
    def fileno(self): # real signature unknown; restored from __doc__
        文件描述符  
         """
        fileno() -> integer "file descriptor".
         
        This is needed for lower-level file interfaces, such os.read().
        """
        return 0    
 
    def flush(self): # real signature unknown; restored from __doc__
        刷新文件內部緩衝區
        """ flush() -> None.  Flush the internal I/O buffer. """
        pass
 
 
    def isatty(self): # real signature unknown; restored from __doc__
        判斷文件是不是贊成tty設備
        """ isatty() -> true or false.  True if the file is connected to a tty device. """
        return False
 
 
    def next(self): # real signature unknown; restored from __doc__
        獲取下一行數據,不存在,則報錯
        """ x.next() -> the next value, or raise StopIteration """
        pass
 
    def read(self, size=None): # real signature unknown; restored from __doc__
        讀取指定字節數據
        """
        read([size]) -> read at most size bytes, returned as a string.
         
        If the size argument is negative or omitted, read until EOF is reached.
        Notice that when in non-blocking mode, less data than what was requested
        may be returned, even if no size parameter was given.
        """
        pass
 
    def readinto(self): # real signature unknown; restored from __doc__
        讀取到緩衝區,不要用,將被遺棄
        """ readinto() -> Undocumented.  Don't use this; it may go away. """
        pass
 
    def readline(self, size=None): # real signature unknown; restored from __doc__
        僅讀取一行數據
        """
        readline([size]) -> next line from the file, as a string.
         
        Retain newline.  A non-negative size argument limits the maximum
        number of bytes to return (an incomplete line may be returned then).
        Return an empty string at EOF.
        """
        pass
 
    def readlines(self, size=None): # real signature unknown; restored from __doc__
        讀取全部數據,並根據換行保存值列表
        """
        readlines([size]) -> list of strings, each a line from the file.
         
        Call readline() repeatedly and return a list of the lines so read.
        The optional size argument, if given, is an approximate bound on the
        total number of bytes in the lines returned.
        """
        return []
 
    def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
        指定文件中指針位置
        """
        seek(offset[, whence]) -> None.  Move to new file position.
         
        Argument offset is a byte count.  Optional argument whence defaults to
(offset from start of file, offset should be >= 0); other values are 1
        (move relative to current position, positive or negative), and 2 (move
        relative to end of file, usually negative, although many platforms allow
        seeking beyond the end of a file).  If the file is opened in text mode,
        only offsets returned by tell() are legal.  Use of other offsets causes
        undefined behavior.
        Note that not all file objects are seekable.
        """
        pass
 
    def tell(self): # real signature unknown; restored from __doc__
        獲取當前指針位置
        """ tell() -> current file position, an integer (may be a long integer). """
        pass
 
    def truncate(self, size=None): # real signature unknown; restored from __doc__
        截斷數據,僅保留指定以前數據
        """
        truncate([size]) -> None.  Truncate the file to at most size bytes.
         
        Size defaults to the current file position, as returned by tell().
        """
        pass
 
    def write(self, p_str): # real signature unknown; restored from __doc__
        寫內容
        """
        write(str) -> None.  Write string str to file.
         
        Note that due to buffering, flush() or close() may be needed before
        the file on disk reflects the data written.
        """
        pass
 
    def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
        將一個字符串列表寫入文件
        """
        writelines(sequence_of_strings) -> None.  Write the strings to the file.
         
        Note that newlines are not added.  The sequence can be any iterable object
        producing strings. This is equivalent to calling write() for each string.
        """
        pass
 
    def xreadlines(self): # real signature unknown; restored from __doc__
        可用於逐行讀取文件,非所有
        """
        xreadlines() -> returns self.
         
        For backward compatibility. File objects now include the performance
        optimizations previously implemented in the xreadlines module.
        """
        pass

2.x
View Code
class TextIOWrapper(_TextIOBase):
    """
    Character and line based layer over a BufferedIOBase object, buffer.
    
    encoding gives the name of the encoding that the stream will be
    decoded or encoded with. It defaults to locale.getpreferredencoding(False).
    
    errors determines the strictness of encoding and decoding (see
    help(codecs.Codec) or the documentation for codecs.register) and
    defaults to "strict".
    
    newline controls how line endings are handled. It can be None, '',
    '\n', '\r', and '\r\n'.  It works as follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.
    
    If line_buffering is True, a call to flush is implied when a call to
    write contains a newline character.
    """
    def close(self, *args, **kwargs): # real signature unknown
        關閉文件
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        文件描述符  
        pass

    def flush(self, *args, **kwargs): # real signature unknown
        刷新文件內部緩衝區
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        判斷文件是不是贊成tty設備
        pass

    def read(self, *args, **kwargs): # real signature unknown
        讀取指定字節數據
        pass

    def readable(self, *args, **kwargs): # real signature unknown
        是否可讀
        pass

    def readline(self, *args, **kwargs): # real signature unknown
        僅讀取一行數據
        pass

    def seek(self, *args, **kwargs): # real signature unknown
        指定文件中指針位置
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        指針是否可操做
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        獲取指針位置
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        截斷數據,僅保留指定以前數據
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        是否可寫
        pass

    def write(self, *args, **kwargs): # real signature unknown
        寫內容
        pass

    def __getstate__(self, *args, **kwargs): # real signature unknown
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

3.x
View Code

注意: 

yang123an
123456789
f = open('e:\\t2.py', mode='r+', encoding='utf-8')
# content = f.read(2)  # read(N) 從頭開始讀取N個字符     ya
# print(content)
f.seek(2)  # 是按照字節定光標的位置開始
content = f.read(3)   #讀取3個字符                               ng1
print(content)  
f.tell()   # 告訴你當前光標的位置
print(f.tell())
# content = f.read()
# print(content)
# f.tell()
# f.readable()  # 是否可讀  返回True  or  False
# line = f.readline()  # 一行一行的讀
# line = f.readlines()  # 每一行當成列表中的一個元素,添加到list中
# f.truncate(4)     #對原文件進行截取一段讀取
# for line in f:
#     print(line)
# f.close()
View Code

 


爲避免打開文件後忘記關閉,能夠經過管理上下文,即:

with open(‘log’,‘r’)as f:

  pass

如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源。

在Python 2.7 及之後,with又支持同時對多個文件的上下文進行管理。

相關文章
相關標籤/搜索