【轉】python檔案開啟檔案詳解——a、a+、r+、w+區別

來源:互聯網
上載者:User

標籤:file   details   分行符號   test   nbsp   python   stdin   str   附加   

原文地址:http://blog.csdn.net/ztf312/article/details/47259805

第一步 排除檔案開啟檔案錯誤:

r唯讀,r+讀寫,不建立

w建立唯寫,w+建立讀寫,二者都會將檔案內容清零

(以w方式開啟,不能讀出。w+可讀寫)

**w+與r+區別:

r+:可讀可寫,若檔案不存在,報錯;w+: 可讀可寫,若檔案不存在,建立

r+與a+區別:

fd = open("1.txt",‘w+‘)  fd.write(‘123‘)  fd = open("1.txt",‘r+‘)  fd.write(‘456‘)  fd = open("1.txt",‘a+‘)  fd.write(‘789‘)

結果:456789

說明r+進行了覆蓋寫。

以a,a+的方式開啟檔案,附加方式開啟

a附加寫方式開啟,不可讀;a+: 附加讀寫方式開啟)

以 ‘U‘ 標誌開啟檔案, 所有的行分割符通過 Python 的輸入方法(例#如 read*() ),返回時都會被替換為分行符號\n. (‘rU‘ 模式也支援 ‘rb‘ 選項) . 

r和U要求檔案必須存在

不可讀的開啟檔案w和a

若不存在會建立新檔案的開啟檔案:a,a+,w,w+

>>> fd=open(r‘f:\mypython\test.py‘,‘w‘)    #唯讀方式開啟,讀取報錯  >>> fd.read()  Traceback (most recent call last):    File "<stdin>", line 1, in <module>  IOError: File not open for reading  >>> fd=open(r‘f:\mypython\test.py‘,‘a‘)#附加寫方式開啟,讀取報錯  >>> fd.read()  Traceback (most recent call last):    File "<stdin>", line 1, in <module>  IOError: File not open for reading  >>></span></span></span>  

 

【轉】python檔案開啟檔案詳解——a、a+、r+、w+區別

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.