加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MySql教程 > 正文

Python个人学习笔记五

发布时间:2020-12-12 02:18:02 所属栏目:MySql教程 来源:网络整理
导读:本节主要学习Python语言的文件处理相关知识 一 第一种python有一系列API默认直接可以引用的函数,这里文件读取函数open在下列表 The Python interpreter has a number of functions and types built into it that are always available. They are listed her
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',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,suffix='',prefix='tmp',dir=None) TemporaryDirectory(suffix='',dir=None) NamedTemporaryFile(mode='w+b',dir=None,delete=True) SpooledTemporaryFile(max_size=0,mode='w+b',dir=None) mktemp(suffix='',dir=None)


示例代码:


import tempfile import os if __name__ == '__main__': print('main :') with tempfile.TemporaryFile('w+t') as tmpNoNameFile: tmpNoNameFile.write('a22222222221111') 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('x22222222221111') 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> a22222222221111a22222222222222a33333333333333a44444444444444 handle---- <tempfile._TemporaryFileWrapper object at 0x0000000002FF3748> x22222222221111x22222222222222x33333333333333x44444444444444 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(),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用户可以自己选择使用,这里就不介绍了。


七  说明


以上大概是基本的文件操作函数和类的一些使用方法,当然还有很多方法和函数可以实现相同功能。

根据个人意愿和需求进行调用。个人觉得那个方便使用哪个,或者自己熟悉那个使用哪个。

本人只是基础学习,整理笔记于此,方便菜鸟和自己后期查阅。


(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

                                    本节主要学习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    
    推荐文章
      热点阅读