多多色-多人伦交性欧美在线观看-多人伦精品一区二区三区视频-多色视频-免费黄色视屏网站-免费黄色在线

國內最全IT社區平臺 聯系我們 | 收藏本站
阿里云優惠2
您當前位置:首頁 > 數據庫 > MySql > Python個人學習筆記五

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用戶可以自己選擇使用,這里就不介紹了。


七  說明


以上大概是基本的文件操作函數和類的一些使用方法,當然還有很多方法和函數可以實現相同功能。

根據個人意愿和需求進行調用。個人覺得那個方便使用哪個,或者自己熟悉那個使用哪個。

本人只是基礎學習,整理筆記于此,方便菜鳥和自己后期查閱。


生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈
程序員人生
------分隔線----------------------------
分享到:
------分隔線----------------------------
關閉
程序員人生
主站蜘蛛池模板: 99久久精品男女性高爱 | 日韩欧美在线第一页 | 最新国产一区二区精品久久 | 伊人999| 五月丁香六月综合缴清无码 | 性欧美videos另类视频 | 成人男女啪啪免费观看网站 | 精品亚洲成a人在线观看 | 亚洲一区二区三区91 | 欧美极品另类 | 豆国产96在线 | 亚洲 | 国内成人自拍视频 | 久草免费网站 | 欧美成人性视频播放 | 在线观看免费xx高清视频 | 免费h视频在线观看 | 一区二区三区在线免费视频 | 亚洲欧美一区二区三区国产精品 | 99久久精品免费国产一区二区三区 | 国内精品免费视频 | 一区二区三区网站 | 久久中文字幕亚洲精品最新 | 久久久久久久99视频 | 亚洲精品亚洲人成毛片不卡 | 视频在线观看网站免费 | 亚洲视频在线看 | 欧美最新一区二区三区四区 | 亚洲精品一区二区乱码在线观看 | 欧美日韩亚洲另类 | 日本性色视频 | 五月婷婷在线视频 | 腿交hd | h视频在线免费观看 | 亚州在线播放 | 老女人毛片 | 久久亚洲国产精品五月天 | 日本欧美一区二区三区视频麻豆 | 成人资源在线观看 | 日本不卡一区二区三区 最新 | 成人啪精品视频免费网站 | 西欧free性video巴西 |