Python個人學習筆記五
來源:程序員人生 發布時間:2014-10-10 08:00:01 閱讀次數:8196次
本節主要學習Python語言的文件處理相關知識
一
第一種python有一系列API默認直接可以引用的函數,這里文件讀取函數open在下列表
The Python interpreter has a number of functions and types built into it that are always available.
They are listed here in alphabetical order.
|
|
Built-in Functions |
|
|
abs() |
dict() |
help() |
min() |
setattr() |
all() |
dir() |
hex() |
next() |
slice() |
any() |
divmod() |
id() |
object() |
sorted() |
ascii() |
enumerate() |
input() |
oct() |
staticmethod() |
bin() |
eval() |
int() |
open() |
str() |
bool() |
exec() |
isinstance() |
ord() |
sum() |
bytearray() |
filter() |
issubclass() |
pow() |
super() |
bytes() |
float() |
iter() |
print() |
tuple() |
callable() |
format() |
len() |
property() |
type() |
chr() |
frozenset() |
list() |
range() |
vars() |
classmethod() |
getattr() |
locals() |
repr() |
zip() |
compile() |
globals() |
map() |
reversed() |
__import__() |
complex() |
hasattr() |
max() |
round() |
|
delattr() |
hash() |
memoryview() |
set() |
|
我們第一個要用的就是open函數。
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
使用示例,這里打開demo.txt文件,位于當前目錄下。自己也可以定義。
代碼里面有兩種讀取方式第一種使用readline第二種使用readlines特別注意
# version v3.4
# date 2014-09-25
import builtins # api
# demo 0
DataArray = []
DataSize = 0
if __name__ == '__main__':
print('main :')
print('-----------read---line-----------')
File_Read = builtins.open('demo.txt', 'r', encoding='UTF-8')
while True:
line = File_Read.readline()
if line:
DataArray.append(line)
CbBytes = line.__len__()
DataSize += CbBytes
else:
GLOBAL_READ_FINISH_STATUS_SUCCESS = True
break
print('data size in bytes : ', DataSize)
File_Read.close()
for index in range(DataArray.__len__()):
print(DataArray[index])
print('-----------read---lines-----------')
DataArray.clear()
File_Read = builtins.open('demo.txt', 'r', encoding='UTF-8')
DataArray = File_Read.readlines()
for index in range(DataArray.__len__()):
print(DataArray[index])
print('exit')
運行結果如下:
main :
-----------read---line-----------
data size in bytes : 558
aricwise9898eman0990
hopelessfo5665ol7676
diegodavty6565i8223
phamvi2328989etcu2332
ale.bosrerereco21211223
shadae.freeman3232232sdsa
alexperry82fdfdq32
emhtyail9fdf263fd2ade
devianai232332dzdz
aricwise9898eman8787
hopelessfo5665ol5445
diegodavty6565i82323
phamvi2328989etcuwqwq
ale.bosrerereco21q
shadae.freeman3232weew
alexperry82fdfdkllk
emhtyail9fdf263fd2rttr
devianai232332gfgf
aricwise9898emang
hopelessfo5665ol609
diegodavty6565i8278
phamvi2328989etcu0-
ale.bosrerereco2190
shadae.freeman323982
alexperry82fdfd45
emhtyail9fdf263fd452
devianai232332334
-----------read---lines-----------
aricwise9898eman0990
hopelessfo5665ol7676
diegodavty6565i8223
phamvi2328989etcu2332
ale.bosrerereco21211223
shadae.freeman3232232sdsa
alexperry82fdfdq32
emhtyail9fdf263fd2ade
devianai232332dzdz
aricwise9898eman8787
hopelessfo5665ol5445
diegodavty6565i82323
phamvi2328989etcuwqwq
ale.bosrerereco21q
shadae.freeman3232weew
alexperry82fdfdkllk
emhtyail9fdf263fd2rttr
devianai232332gfgf
aricwise9898emang
hopelessfo5665ol609
diegodavty6565i8278
phamvi2328989etcu0-
ale.bosrerereco2190
shadae.freeman323982
alexperry82fdfd45
emhtyail9fdf263fd452
devianai232332334
exit
二
第二種這種文件讀取采用linecache操作模塊。該模塊總共有以下五個函數
linechche是一種高校區文本文件模塊。從文件獲取文本行,維護一個結果緩存,
從而實現高效的讀取多行文本。其中可以快速的讀取指定的某一行。
示例代碼:
def getline(filename, lineno, module_globals=None):
def clearcache():
def getlines(filename, module_globals=None):
def checkcache(filename=None):
def updatecache(filename, module_globals=None):
示例代碼如下,這里既使用getline函數也使用了getlines函數。
其中區別讀者自己調試觀察。
示例代碼:
import linecache
# demo 1
if __name__ == '__main__':
print('main :')
line = linecache.getline('demo.txt', 13)
if line == '':
print('index out of range')
else:
print(line)
lines = linecache.getlines('demo.txt')
for lineIndex in lines:
print(lineIndex)
linecache.clearcache()
print('exit')
運行結果如下:
main :
phamvi2328989etcuwqwq
aricwise9898eman0990
hopelessfo5665ol7676
diegodavty6565i8223
phamvi2328989etcu2332
ale.bosrerereco21211223
shadae.freeman3232232sdsa
alexperry82fdfdq32
emhtyail9fdf263fd2ade
devianai232332dzdz
aricwise9898eman8787
hopelessfo5665ol5445
diegodavty6565i82323
phamvi2328989etcuwqwq
ale.bosrerereco21q
shadae.freeman3232weew
alexperry82fdfdkllk
emhtyail9fdf263fd2rttr
devianai232332gfgf
aricwise9898emang
hopelessfo5665ol609
diegodavty6565i8278
phamvi2328989etcu0-
ale.bosrerereco2190
shadae.freeman323982
alexperry82fdfd45
emhtyail9fdf263fd452
devianai232332334
exit
三
第三種方式采用tempfile模塊實現。
tempfile臨時文件系統對象。python使用tempfile創建
一系列安全的臨時文件系統資源
主要函數如下。這里我們測試一下它的臨時匿名文件和命名文件函數
TemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None)
TemporaryDirectory(suffix='', prefix='tmp', dir=None)
NamedTemporaryFile(mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None, delete=True)
SpooledTemporaryFile(max_size=0, mode='w+b', buffering=None, encoding=None, newline=None, suffix='', prefix='tmp', dir=None)
mktemp(suffix='', prefix='tmp', dir=None)
示例代碼:
import tempfile
import os
if __name__ == '__main__':
print('main :')
with tempfile.TemporaryFile('w+t') as tmpNoNameFile:
tmpNoNameFile.write('a11111111111111')
tmpNoNameFile.write('a22222222222222')
tmpNoNameFile.write('a33333333333333')
tmpNoNameFile.write('a44444444444444')
tmpNoNameFile.seek(0)
print('handle----', tmpNoNameFile)
for tmp in tmpNoNameFile:
print(tmp)
tmpNoNameFile.close()
with tempfile.NamedTemporaryFile('w+t') as tmpNameFile:
tmpNameFile.write('x11111111111111')
tmpNameFile.write('x22222222222222')
tmpNameFile.write('x33333333333333')
tmpNameFile.write('x44444444444444')
tmpNameFile.seek(0)
print('handle----', tmpNameFile)
for tmp in tmpNameFile:
print(tmp)
tmpNameFile.close()
tmpDir = tempfile.mkdtemp()
print(tmpDir)
os.removedirs(tmpDir)
print(tmpDir)
print('exit')
運行結果如下:
main :
handle---- <tempfile._TemporaryFileWrapper object at 0x0000000002CCDF98>
a11111111111111a22222222222222a33333333333333a44444444444444
handle---- <tempfile._TemporaryFileWrapper object at 0x0000000002FF3748>
x11111111111111x22222222222222x33333333333333x44444444444444
C:UsersROOTAppDataLocalTemp mpkgijyiqb
C:UsersROOTAppDataLocalTemp mpkgijyiqb
exit
這里說明一下,臨時文件系統資源,會在文件關閉時候自動刪除。
但是目錄不行,必須自己手動刪除,注意這行代碼
<span style="font-size:12px;">os.removedirs(tmpDir)</span>
四
第四種是文件操作是文件的拷貝直接利用shutil模塊提供的相關函數即可。
這個模塊可以做一些高級操作,比如設置文件的一些屬性和權限。
示例代碼:
import shutil
import os
if __name__ == '__main__':
print('main :')
try:
shutil.copy('demo.txt', 'des.txt')
except IOError:
print(IOError.errno)
os.chmod('demo.txt', 0x444)
print('exit')
五
第五種使用的內存映射文件,類似于windows的映射。
內存映射通常可以提供I/O性能,因為使用內存映射時,不會對每個訪問都有一個
單獨的系統調用,而且不需要緩沖區進行復制數據,可以再內核和用戶之間方便的共享數據
和內存。
示例代碼:
import builtins
import mmap
import contextlib
if __name__ == '__main__':
print('main :')
file = builtins.open('demo.txt', 'r')
with contextlib.closing(mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ)) as mm:
print(mm.read(10))
print(mm[:100])
print('exit')
運行結果如下:
main :
b'aricwise98'
b'aricwise9898eman0990
hopelessfo5665ol7676
diegodavty6565i8223
phamvi2328989etcu2332
ale.bosrerer'
exit
六
第六種使用StringIO模塊實現對文件的操作。
StringIO提供了一種簡單的做法,可以使用api(read() write()等等)處理內存中的文本。
有兩種不同的實現cStringIO版本使用C語言編寫以提高速度,而StringIO使用Python
語言編寫來提高可移植性。與其他的以下字符串鏈接操作相比,使用C語言版本的構造
大字符串可以提供更好的性能。
示例代碼
import io
if __name__ == '__main__':
print('main :')
IO_FILE = io.StringIO()
IO_FILE.write('xxxxxxxxxxxx')
IO_FILE.writelines('yyyyyyyyyyy')
tmp = IO_FILE.getvalue()
print(tmp)
IO_FILE.close()
print('exit')
運行結果如下:
main :
xxxxxxxxxxxxyyyyyyyyyyy
exit
cStringIO用戶可以自己選擇使用,這里就不介紹了。
七 說明
以上大概是基本的文件操作函數和類的一些使用方法,當然還有很多方法和函數可以實現相同功能。
根據個人意愿和需求進行調用。個人覺得那個方便使用哪個,或者自己熟悉那個使用哪個。
本人只是基礎學習,整理筆記于此,方便菜鳥和自己后期查閱。
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈