ファイル操作のオープンファイル


一、ファイルを開く
obj = open('    ','      ')
       :
r:    
r+:   rw
w:    
w+:    w,   
a:    
a+:    a,   
open() Python     ,        /  (I/O)       ,               ,    IOError  ,file()       , open    ,    ,       open(),  open() Python    。file            

2つの方法を導入します.
obj.tell()
tell              /        。(              )
obj.seek()
             。      0             (       ),1            (       )

サンプルコードは次のとおりです.
obj = open('log.py','r')
obj.seek(5)  ---------->            5     ,       
print obj.tell() ------->       .( 5        )
print obj.read() ------->         
print obj.tell() ------->       
obj.close()     --------->    

log.pyの内容は次のとおりです.
11111111222222
    :511122222216
  r+      
      :
__author__ = 'ryan'obj = open('log.py','r+')print obj.tell()obj.write('##########')obj.close()

log.pyの内容は次のとおりです.
111111122222222
      ,  log.py  
##########2222222
   r+    ,     ,            ( 0  )     0           ,             ;

次のコードを見て、ポインタの位置を8バイト目の位置に移動し、書き込み*を実行します.
__author__ = 'ryan'obj = open('log.py','r+')print obj.seek(8)
print obj.tell()
obj.write('*************')obj.close()

logを表示します.py結果
########*************
8番目の場所からアスタリスク(*)の書き込みを開始
次に、(上記のコードにtruncate()メソッドを追加するとともに、ポインタをファイルの開始位置(すなわち0位置)に復元します.
__author__ = 'ryan'
obj = open('log.py','r+')print obj.tell()
obj.write('@@@@@@')
obj.truncate()
obj.close()

logを再観察する.pyの内容は次のとおりです.
@@@@@@
5個の@記号を発見した後の内容はすべてなく、5個の@記号を切り取った後のすべての内容
次のコードを見てください.
obj = open('log.py','rb')print obj.tell()obj.write('@@@@@@')obj.truncate()obj.close()

ここで「rb」は、linux上のファイルがバイナリで格納されているため、プラットフォーム間でbを追加する場合、バイナリでファイルを読み取ります.Windowsではbを付ける必要があります
まとめ:
ファイルを操作する場合、一般的には、ファイルを開く操作ファイル1、ファイルを開く1ファイルハンドル=file('ファイルパス','モード')注:pythonでファイルを開くにはopen(...)の2つの方法があります.ファイル(...)、本質的に前者は内部で後者を呼び出してファイル操作を行い、openの使用を推奨します.ファイルを開くときは、ファイルのパスとどのようにファイルを開くかを指定する必要があります.開くと、そのファイルハンドルが取得され、後でこのファイルハンドルでファイルが操作されます.ファイルを開くモードは、r、読み取り専用モード(デフォルト)です.w、書き込みモードのみ.【読み取り不可、存在しない場合作成、存在する場合削除内容】a,追加モード.【可読、存在しなければ作成、存在しなければコンテンツのみ追加】「+」は、あるファイルr+を同時に読み書きでき、読み書き可能なファイルを表す.【可読;書込み可能;追加可能】w+、書込みa+、同a“U”は、読み取り時に、rrを自動的に(rまたはr+モードと併用する)rU r+U“b”に変換することができることを示し、処理バイナリファイル(例えば、FTPはISOミラーファイルをアップロードし、linuxは無視でき、windowsはバイナリファイルを処理する際に表示する必要がある)rb wb ab二、操作ファイル
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        0 (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