python中如何對(duì)文件進(jìn)行讀寫(xiě)操作?針對(duì)這個(gè)問(wèn)題,今天小編總結(jié)這篇有關(guān)文件讀寫(xiě)的文章,希望能幫助更多想解決這個(gè)問(wèn)題的朋友找到更加簡(jiǎn)單易行的辦法。

open(filemode='r'buffering=-1encoding=Noneerrors=Nonenewline=Noneclosefd=Trueopener=None)
| Character | Meaning |
|---|---|
'r' | open for reading (default) |
'w' | open for writing, truncating the file first |
'x' | open for exclusive creation, failing if the file already exists |
'a' | open for writing, appending to the end of the file if it exists |
'b' | binary mode |
't' | text mode (default) |
'+' | open a disk file for updating (reading and writing) |
'U' | universal newlines mode (deprecated) |
The default mode is 'r' (open for reading text, synonym of 'rt'). For binary read-write access, the mode 'w+b' opens and truncates the file to 0 bytes. 'r+b' opens the file without truncation.
文本讀寫(xiě)操作:open(), close(), read(), readlines(),
一、普通操作,open(),read(),close()
#!/usr/bin/python
#coding=utf-8
import logging
try:
f = open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r')
print f.read();
print 'read'
except Exception as e:
logging.exception(e)
print 'error'
raise
finally:
if f:
f.close()
print 'OK'運(yùn)行結(jié)果:
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Dict(dict):
def __init__(self, **kw):
super().__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value
read
OK二、read()完后自動(dòng)close()
with open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r') as f:
print (f.read())運(yùn)行結(jié)果:
#!/usr/bin/python
# -*- coding: utf-8 -*-
class Dict(dict):
def __init__(self, **kw):
super().__init__(**kw)
def __getattr__(self, key):
try:
return self[key]
except KeyError:
raise AttributeError(r"'Dict' object has no attribute '%s'" % key)
def __setattr__(self, key, value):
self[key] = value三、為避免read()未知容量的大文件,保險(xiǎn)起見(jiàn)用readlines().
print '------------------------------------'
print '-----------------------------------'
f = open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r')
for line in f.readlines():
print(line.strip()) ##strip會(huì)將前面首字符前的空格去掉,造成行句沒(méi)有縮進(jìn)
f.close()
print 'over'運(yùn)行結(jié)果:
------------------------------------ ----------------------------------- #!/usr/bin/python # -*- coding: utf-8 -*- class Dict(dict): def __init__(self, **kw): super().__init__(**kw) def __getattr__(self, key): try: return self[key] except KeyError: raise AttributeError(r"'Dict' object has no attribute '%s'" % key) def __setattr__(self, key, value): self[key] = value over
四、讀二進(jìn)制文件,如圖片,視頻等
>>> f = open('/Users/michael/test.jpg', 'rb')
>>> f.read()
b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...' # 十六進(jìn)制表示的字節(jié)五、write()
with open('/home/seeing-zynq/Documents/Temp/IO/a.txt', 'w') as f:
f.write('haha')
with open('/home/seeing-zynq/Documents/Temp/IO/a.txt', 'r') as f:
print (f.read())
"file.py" 37L, 758C wri運(yùn)行結(jié)果:
haha
看完上述內(nèi)容,你們對(duì)python中的文件讀寫(xiě)操作大概了解了嗎?如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝各位的閱讀!
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿(mǎn)足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。
名稱(chēng)欄目:python中的文件讀寫(xiě)操作-創(chuàng)新互聯(lián)
網(wǎng)頁(yè)URL:http://chinadenli.net/article6/digcig.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供微信小程序、移動(dòng)網(wǎng)站建設(shè)、自適應(yīng)網(wǎng)站、響應(yīng)式網(wǎng)站、網(wǎng)站改版、品牌網(wǎng)站制作
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶(hù)投稿、用戶(hù)轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話(huà):028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來(lái)源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容
營(yíng)銷(xiāo)型網(wǎng)站建設(shè)知識(shí)