日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

文件操作(初阶)

發布時間:2024/8/26 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 文件操作(初阶) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

操作文件時,一般需要經歷如下步驟:

  • 打開文件
  • 操作文件
  • 關閉文件
#open()是python的內置函數,而read()、close()等都是屬于TextIOWrapper類的,詳情參見源碼。f = open('1.txt', 'r') #打開文件 data = f.read() #操作文件 f.close() #關閉文件 print(data)

一、打開文件

文件在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

總結

以上是生活随笔為你收集整理的文件操作(初阶)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。