標籤: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+區別