
EC君
閑白
Hello大家好我是EC君
今天為大家簡(jiǎn)單介紹下Python中的文件處理,文件各種虐戀處理在Python中是最常用到的坑之一。
下面開(kāi)始正題吧。
OK:不要干,就是慫。Here we go!
</br>
對(duì)文件操作流程
- 1.打開(kāi)文件,得到文件句柄并賦值給一個(gè)變量
- 2.通過(guò)句柄對(duì)文件進(jìn)行操作
- 3.關(guān)閉文件
我們現(xiàn)在有一個(gè)文件:
行路難
李白
金樽清酒斗十千,玉盤(pán)珍羞直萬(wàn)錢(qián)。
停杯投箸不能食,拔劍四顧心茫然。
欲渡黃河冰塞川,將登太行雪滿(mǎn)山。
閑來(lái)垂釣碧溪上,忽復(fù)乘舟夢(mèng)日邊。
行路難,行路難,多歧路,今安在。
長(zhǎng)風(fēng)破浪會(huì)有時(shí),直掛云帆濟(jì)滄海。
基本操作
f = open('lyrics') # 打開(kāi)文件
first_line = f.readline()
print('first line:', first_line) # 讀一行
print('我是分隔線(xiàn)'.center(50, '-'))data = f.read() # 讀取剩下的所有內(nèi)容,文件大時(shí)不要用
print(data) # 打印文件
f.close() # 關(guān)閉文件
打開(kāi)文件模:
- r,只讀模式(默認(rèn))
- w,只寫(xiě)模式。不可讀:不存在則創(chuàng)建;存在則刪除內(nèi)容
- a,追加模式??勺x:不存在則創(chuàng)建;存在則只追加內(nèi)容
"+" 表示可以同時(shí)讀寫(xiě)某個(gè)文件
- r+,可讀寫(xiě)文件。可讀;可寫(xiě);可追加
- w+,寫(xiě)讀
- a+,同a
"U"表示在讀取時(shí),可以將 \r \n \r\n自動(dòng)轉(zhuǎn)換成 \n (與 r 或 r+ 模式同使用)
- rU
- r+U
"b"表示處理二進(jìn)制文件(如:FTP發(fā)送上傳ISO鏡像文件,linux可忽略,windows處理二進(jìn)制文件時(shí)需標(biāo)注)
- rb
- wb
- ab
其它語(yǔ)法
def close(self): # real signature unknown; restored from __doc__
"""
Close the file.
A closed file cannot be used for further I/O operations. close() may be
called more than once without error.
"""
pass
def fileno(self, *args, **kwargs): # real signature unknown
""" Return the underlying file descriptor (an integer). """
pass
def isatty(self, *args, **kwargs): # real signature unknown
""" True if the file is connected to a TTY device. """
pass
def read(self, size=-1): # known case of _io.FileIO.read
"""
注意,不一定能全讀回來(lái)
Read at most size bytes, returned as bytes.
Only makes one system call, so less data may be returned than requested.
In non-blocking mode, returns None if no data is available.
Return an empty bytes object at EOF.
"""
return ""
def readable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a read mode. """
pass
def readall(self, *args, **kwargs): # real signature unknown
"""
Read all data from the file, returned as bytes.
In non-blocking mode, returns as much as is immediately available,
or None if no data is available. Return an empty bytes object at EOF.
"""
pass
def readinto(self): # real signature unknown; restored from __doc__
""" Same as RawIOBase.readinto(). """
pass #不要用,沒(méi)人知道它是干嘛用的
def seek(self, *args, **kwargs): # real signature unknown
"""
Move to new file position and return the file position.
Argument offset is a byte count. Optional argument whence defaults to
SEEK_SET or 0 (offset from start of file, offset should be >= 0); other values
are SEEK_CUR or 1 (move relative to current position, positive or negative),
and SEEK_END or 2 (move relative to end of file, usually negative, although
many platforms allow seeking beyond the end of a file).
Note that not all file objects are seekable.
"""
pass
def seekable(self, *args, **kwargs): # real signature unknown
""" True if file supports random-access. """
pass
def tell(self, *args, **kwargs): # real signature unknown
"""
Current file position.
Can raise OSError for non seekable files.
"""
pass
def truncate(self, *args, **kwargs): # real signature unknown
"""
Truncate the file to at most size bytes and return the truncated size.
Size defaults to the current file position, as returned by tell().
The current file position is changed to the value of size.
"""
pass
def writable(self, *args, **kwargs): # real signature unknown
""" True if file was opened in a write mode. """
pass
def write(self, *args, **kwargs): # real signature unknown
"""
Write bytes b to file, return number written.
Only makes one system call, so not all of the data may be written.
The number of bytes actually written is returned. In non-blocking mode,
returns None if the write would block.
"""
pass
with語(yǔ)句
為了避免打開(kāi)文件后忘記關(guān)閉,可以通過(guò)管理上下文,即:
with open('log','r') as f:
...
如此方式,當(dāng)with代碼塊執(zhí)行完畢時(shí),內(nèi)部會(huì)自動(dòng)關(guān)閉并釋放文件資源。
在Python 2.7 后,with又支持同時(shí)對(duì)多個(gè)文件的上下文進(jìn)行管理,即:
with open('log1') as obj1, open('log2') as obj2:
pass
END.
OK今天就為大家介紹這么多了。
我是EC君,如果你喜歡我的文章,請(qǐng)幫忙點(diǎn)個(gè)關(guān)注!點(diǎn)個(gè)喜歡吧!
也可以點(diǎn)擊作者信息,掃描微信二維碼關(guān)注我的個(gè)人微信公眾號(hào)。
你的鼓勵(lì)將是我們共同進(jìn)步的源泉。