溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

python中的文件讀寫操作

發(fā)布時間:2020-05-25 10:59:46 來源:億速云 閱讀:133 作者:Leah 欄目:編程語言

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

open(filemode='r'buffering=-1encoding=Noneerrors=Nonenewline=Noneclosefd=Trueopener=None)

CharacterMeaning
'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.

文本讀寫操作: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'

運行結(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()完后自動close()

with open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r') as f:    
	print (f.read())

運行結(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()未知容量的大文件,保險起見用readlines().

print '------------------------------------'
print '-----------------------------------'
f = open('/home/seeing-zynq/Documents/Temp/Test/mydict.py', 'r')
for line in f.readlines():
    print(line.strip())  ##strip會將前面首字符前的空格去掉,造成行句沒有縮進
f.close()
print 'over'

運行結(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


四、讀二進制文件,如圖片,視頻等

>>> f = open('/Users/michael/test.jpg', 'rb')
>>> f.read()
b'\xff\xd8\xff\xe1\x00\x18Exif\x00\x00...' # 十六進制表示的字節(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

運行結(jié)果:

haha

看完上述內(nèi)容,你們對python中的文件讀寫操作大概了解了嗎?如果想了解更多相關(guān)文章內(nèi)容,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI