码迷,mamicode.com
首页 > 编程语言 > 详细

Python个人学习笔记五

时间:2014-09-26 21:12:18      阅读:430      评论:0      收藏:0      [点我收藏+]

标签:python   文件系统   api   数据   lines   

                                    本节主要学习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:\Users\ROOT\AppData\Local\Temp\tmpkgijyiqb
C:\Users\ROOT\AppData\Local\Temp\tmpkgijyiqb
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\r\nhopelessfo5665ol7676\r\ndiegodavty6565i8223\r\nphamvi2328989etcu2332\r\nale.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   数据   lines   

原文地址:http://blog.csdn.net/microzone/article/details/39580059

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!