您好,登錄后才能下訂單哦!
一、打開文件
obj = open('文件路徑','打開文件方式') 打開文件方式有: r:只讀方式 r+:相當于rw w:寫入方式 w+:仍然等于w,無意義 a:追加方式 a+:仍然等于a,無意義 open()是Python的內建函數,提供了初始化輸入/輸出(I/O)的操作通用接口,成功打開一個文件后返回一個對象,否則發生IOError異常,file()是一個工廠函數,與open方法一樣,可以互換,但是一般推薦用open(),因為open()是Python內建函數。file后期會被合并掉其他函數內
引入兩個方法:
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內容如下
1
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'是以二進制的方式讀取文件,如果跨平臺即要加上b,因為linux上文件都是以二進制進行存放的。而在windows上則需要加上b
小結:
操作文件時,一般需要經歷如下步驟:
打開文件
操作文件
一、打開文件
1
文件句柄 = file('文件路徑', '模式')
注:python中打開文件有兩種方式,即:open(...) 和 file(...) ,本質上前者在內部會調用后者來進行文件操作,推薦使用 open。
打開文件時,需要指定文件路徑和以何等方式打開文件,打開后,即可獲取該文件句柄,日后通過此文件句柄對該文件操作。
打開文件的模式有:
r,只讀模式(默認)。
w,只寫模式。【不可讀;不存在則創建;存在則刪除內容;】
a,追加模式。【可讀; 不存在則創建;存在則只追加內容;】
"+" 表示可以同時讀寫某個文件
r+,可讀寫文件。【可讀;可寫;可追加】
w+,寫讀
a+,同a
"U"表示在讀取時,可以將 \r \n \r\n自動轉換成 \n (與 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
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。