python-open文件處理

来源:http://www.cnblogs.com/tiannan/archive/2016/12/23/6215634.html
-Advertisement-
Play Games

python內置函數open()用於打開文件和創建文件對象 語法 name:文件名 mode:指定文件的打開模式 r:只讀 w:寫入 a:附加 r+,w+,a+同時支持輸入輸出操作 rb,wb+以二進位方式打開 bufsize:定義輸出緩存 0表示無輸出緩存 1表示使用緩衝 負數表示使用系統預設設置 ...


python內置函數open()用於打開文件和創建文件對象

語法

open(name[,mode[,bufsize]])

 

name:文件名

mode:指定文件的打開模式

  r:只讀

  w:寫入

  a:附加

  r+,w+,a+同時支持輸入輸出操作

  rb,wb+以二進位方式打開

bufsize:定義輸出緩存

  0表示無輸出緩存

  1表示使用緩衝

  負數表示使用系統預設設置

  正數表示使用近似指定大小的緩衝

 

#以只讀方式打開text.txt文件,賦值給f1變數
>>> f1 = open('test.txt','r')

#查看f1數據類型
>>> type(f1)
<class '_io.TextIOWrapper'>

#讀取文件內容,以字元串形式返回
>>> f1.read()
'h1\nh2\nh3\nh4\nh5\nh6'

#此時指針處於文件末尾,通過tell獲取當前指針位置,通過seek重新指定指針位置
>>> f1.readline()
''
>>> f1.tell()
22

>>> f1.seek(0)
0

#單行讀取
>>> f1.readline()
'h1\n'

#讀取餘下所有行,以列表方式返回
>>> f1.readlines()
['h2\n', 'h3\n', 'h4\n', 'h5\n', 'h6']

#文件名
>>> f1.name
'test.txt'

#關閉文件
>>> f1.close()

#文件寫入
f2 = open('test.txt','w+')
f2.write('hello')
f2.close()

#向文件追加內容
f3 = open('test.txt','a')
f3.write('hello')
f3.close()

#通過flush,將緩衝區內容寫入文件
#write將字元串值寫入文件
f3 = open('test.txt','w+')
for line in (i**2 for i in range(1,11)):
    f3.write(str(line)+'\n')
f3.flush()
#f3.close()

#writelines將列表值寫入文件
f3 = open('test.txt','w+')
lines = ['11','22','33','44']
f3.writelines(lines)
f3.seek(0)
print(f3.readlines())
f3.close()
#執行結果:['11223344']

>>> f3.closed
True
>>> f3.mode
'w+'
>>> f3.encoding
'cp936'
Help on TextIOWrapper object:

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.
 |  
 |  Method resolution order:
 |      TextIOWrapper
 |      _TextIOBase
 |      _IOBase
 |      builtins.object
 |  
 |  Methods defined here:
 |  
 |  __getstate__(...)
 |  
 |  __init__(self, /, *args, **kwargs)
 |      Initialize self.  See help(type(self)) for accurate signature.
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  close(self, /)
 |      Flush and close the IO object.
 |      
 |      This method has no effect if the file is already closed.
 |  
 |  detach(self, /)
 |      Separate the underlying buffer from the TextIOBase and return it.
 |      
 |      After the underlying buffer has been detached, the TextIO is in an
 |      unusable state.
 |  
 |  fileno(self, /)
 |      Returns underlying file descriptor if one exists.
 |      
 |      OSError is raised if the IO object does not use a file descriptor.
 |  
 |  flush(self, /)
 |      Flush write buffers, if applicable.
 |      
 |      This is not implemented for read-only and non-blocking streams.
 |  
 |  isatty(self, /)
 |      Return whether this is an 'interactive' stream.
 |      
 |      Return False if it can't be determined.
 |  
 |  read(self, size=-1, /)
 |      Read at most n characters from stream.
 |      
 |      Read from underlying buffer until we have n characters or we hit EOF.
 |      If n is negative or omitted, read until EOF.
 |  
 |  readable(self, /)
 |      Return whether object was opened for reading.
 |      
 |      If False, read() will raise OSError.
 |  
 |  readline(self, size=-1, /)
 |      Read until newline or EOF.
 |      
 |      Returns an empty string if EOF is hit immediately.
 |  
 |  seek(self, cookie, whence=0, /)
 |      Change stream position.
 |      
 |      Change the stream position to the given byte offset. The offset is
 |      interpreted relative to the position indicated by whence.  Values
 |      for whence are:
 |      
 |      * 0 -- start of stream (the default); offset should be zero or positive
 |      * 1 -- current stream position; offset may be negative
 |      * 2 -- end of stream; offset is usually negative
 |      
 |      Return the new absolute position.
 |  
 |  seekable(self, /)
 |      Return whether object supports random access.
 |      
 |      If False, seek(), tell() and truncate() will raise OSError.
 |      This method may need to do a test seek().
 |  
 |  tell(self, /)
 |      Return current stream position.
 |  
 |  truncate(self, pos=None, /)
 |      Truncate file to size bytes.
 |      
 |      File pointer is left unchanged.  Size defaults to the current IO
 |      position as reported by tell().  Returns the new size.
 |  
 |  writable(self, /)
 |      Return whether object was opened for writing.
 |      
 |      If False, write() will raise OSError.
 |  
 |  write(self, text, /)
 |      Write string to stream.
 |      Returns the number of characters written (which is always equal to
 |      the length of the string).
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors defined here:
 |  
 |  buffer
 |  
 |  closed
 |  
 |  encoding
 |      Encoding of the text stream.
 |      
 |      Subclasses should override.
 |  
 |  errors
 |      The error setting of the decoder or encoder.
 |      
 |      Subclasses should override.
 |  
 |  line_buffering
 |  
 |  name
 |  
 |  newlines
 |      Line endings translated so far.
 |      
 |      Only line endings translated during reading are considered.
 |      
 |      Subclasses should override.
 |  
 |  ----------------------------------------------------------------------
 |  Methods inherited from _IOBase:
 |  
 |  __del__(...)
 |  
 |  __enter__(...)
 |  
 |  __exit__(...)
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  readlines(self, hint=-1, /)
 |      Return a list of lines from the stream.
 |      
 |      hint can be specified to control the number of lines read: no more
 |      lines will be read if the total size (in bytes/characters) of all
 |      lines so far exceeds hint.
 |  
 |  writelines(self, lines, /)
 |  
 |  ----------------------------------------------------------------------
 |  Data descriptors inherited from _IOBase:
 |  
 |  __dict__
View Code

 


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 變數 、緩衝值 、編碼 --道心 變數 聲明變數 eg: #!/usr/bin/env python # -*- coding: utf-8 -*- name = "DaoXin" 上述代碼聲明瞭一個變數,變數名為: name,變數name的值為:"DaoXin" 變數的作用:昵稱,其代指記憶體里某個 ...
  • "fatal.h"//頭文件 1 #include<stdio.h> 2 #include<stdlib.h> 3 #define Error(Str) FatalError(Str) 4 #define FatalError(Str) fprintf(stderr,"%s\n",Str),exit ...
  • 樣式表的幾點常用:background-color: 背景顏色 background-image:url 設置圖片背景 background-repeat平鋪 repeat-x 橫向平鋪 background-position:center 背景居中 background-position:righ ...
  • 這個鏈表是帶有表頭的單鏈表。實現鏈表的一些規範操作,初始化,插入,刪除等。包括兩個頭文件list.h,fatal.h,庫函數list.c,測試函數testlist.c。頭文件放的都是函數聲明,庫函數list.c放的的函數的定義。 頭文件list.h 頭文件fatal.h: 庫函數list.c: 測試 ...
  • 觀察者模式由四個角色組成:抽象主題角色,抽象觀察者角色,具體主題角色,抽象觀察者角色,具體觀察者角色。 抽象主題角色(Subject):把所有的觀察者角色的引用保存在一個集合中,可以有任意數量的觀察者。其提供一個介面,可以添加、刪除觀察者,並可以向登記過的觀察者發送通知。 具體主題角色(Observ ...
  • 樹狀數組套主席樹模板題。。。 題目大意: 給定一個含有n個數的序列a[1],a[2],a[3]……a[n],程式必須回答這樣的詢問:對於給定的i,j,k,在a[i],a[i+1],a[i+2]……a[j]中第k小的數是多少(1≤k≤j-i+1),並且,你可以改變一些a[i]的值,改變後,程式還能針對 ...
  • 一、字元串操作 創建字元串 String s2 = new String("Hello World"); String s1 = "Hello World"; 1.字元串連接 多個字元串鏈接時,每個字元串之間用+相連,+就是字元串鏈接,連接之後生成一個新的字元串。 2.獲取字元串長度 a.lengh ...
  • Swift相關知識,有時間就敲點,供自己學習總結,亦或也有幸能幫到他人,有理解、使用錯誤的地方也望能得到指正。 ///******************************************************************************************* ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...