文件操作(初阶)
操作文件時,一般需要經歷如下步驟:
- 打開文件
- 操作文件
- 關閉文件
一、打開文件
文件在open的時候是不會被加到內存中的,只有read或write的時候才會加到內存中。
打開文件的模式有:
r ,只讀模式【默認】
w,只寫模式【不可讀;不存在則創建;存在則清空內容;】
x, 只寫模式【不可讀;不存在則創建,存在則報錯】
a, 追加模式【可讀; 不存在則創建;存在則只追加內容;】
"+" 表示可以同時讀寫某個文件:
r+, 讀寫【可讀,可寫】,從開始向后讀,寫和追加的時候指針會調到最后
w+,寫讀【可讀,可寫】,先清空數據,從開始向后讀,寫和追加的時候指針會調到最后
x+ ,寫讀【可讀,可寫】,同上
a+, 寫讀【可讀,可寫】,同上
"b"表示以字節的方式操作:
rb 或 r+b
wb 或 w+b
xb 或 w+b
ab 或 a+b
注:以b方式打開時,讀取到的內容是字節類型,寫入時也需要提供字節類型
二、操作文件
class TextIOWrapper(_TextIOBase):"""Character and line based layer over a BufferedIOBase object, buffer.encoding gives the name of the encoding that the stream will bedecoded or encoded with. It defaults to locale.getpreferredencoding(False).errors determines the strictness of encoding and decoding (seehelp(codecs.Codec) or the documentation for codecs.register) anddefaults 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 isenabled. Lines in the input can end in '\n', '\r', or '\r\n', andthese are translated into '\n' before being returned to thecaller. If it is '', universal newline mode is enabled, but lineendings are returned to the caller untranslated. If it has any ofthe other legal values, input lines are only terminated by the givenstring, and the line ending is returned to the caller untranslated.* On output, if newline is None, any '\n' characters written aretranslated to the system default line separator, os.linesep. Ifnewline is '' or '\n', no translation takes place. If newline is anyof the other legal values, any '\n' characters written are translatedto the given string.If line_buffering is True, a call to flush is implied when a call towrite contains a newline character."""def close(self, *args, **kwargs): """關閉文件""" passdef detach(self, *args, **kwargs): passdef fileno(self, *args, **kwargs): """文件描述符""" passdef flush(self, *args, **kwargs): """把緩沖區的內容寫入硬盤"""passdef isatty(self, *args, **kwargs): passdef read(self, *args, **kwargs): """讀取指定字節數據"""passdef readable(self, *args, **kwargs): passdef readline(self, *args, **kwargs): """只讀取一行數據"""passdef seek(self, *args, **kwargs): """指定文件中指針位置f.seek(0) 把指針歸零"""passdef seekable(self, *args, **kwargs): passdef tell(self, *args, **kwargs): """獲取當前指針位置"""passdef truncate(self, *args, **kwargs): passdef writable(self, *args, **kwargs): passdef write(self, *args, **kwargs): passdef __getstate__(self, *args, **kwargs): passdef __init__(self, *args, **kwargs): pass@staticmethod # known case of __new__def __new__(*args, **kwargs): """ Create and return a new object. See help(type) for accurate signature. """passdef __next__(self, *args, **kwargs): """ Implement next(self). """passdef __repr__(self, *args, **kwargs): """ Return repr(self). """pass三、關閉文件
使用open打開文件后一定要記得調用文件對象的close()方法。比如可以用try/finally語句來確保最后能關閉文件。
file_object = open('thefile.txt') try:all_the_text = file_object.read( ) finally:file_object.close( )注:不能把open語句放在try塊里,因為當打開文件出現異常時,文件對象file_object無法執行close()方法。四、代碼塊
創建代碼塊能實現的功能:
1、每次操作完后不用再次手動關閉
2、能同時打開兩個文件(2.7之后才有的功能)
批量操作
with open('1.txt', 'r') as f1, open('2.txt','r') as f2:pass模擬文件復制的過程(針對大文件比較有效)
with open('1.txt', 'r') as f1, open('2.txt','w') as f2:for line in f1: #讀取原文件內容,然后一行一行寫到新文件中f2.write(line)轉載于:https://www.cnblogs.com/whatisfantasy/p/5967288.html
總結
- 上一篇: OV7725学习之SCCB协议(一)
- 下一篇: Oracle中的存储过程简单例子