python文件操作

来源:互联网 发布:开淘宝网店策划书范文 编辑:程序博客网 时间:2024/05/27 19:27

文件的输入输出 file-io

关于文件的打开模式有以下标志,需牢记!!!
这里写图片描述

Python File(文件) 方法

file 对象使用 open 函数来创建,下图列出了 file 对象常用的函数:
这里写图片描述

In [0]: fo = open('/bao/file','wb')#打开文件In [1]: fo.#文件操作的方法fo.close       fo.flush       fo.next        fo.seek        fo.writelinesfo.closed      fo.isatty      fo.read        fo.softspace   fo.xreadlinesfo.encoding    fo.mode        fo.readinto    fo.tell        fo.errors      fo.name        fo.readline    fo.truncate    fo.fileno      fo.newlines    fo.readlines   fo.write       In [2]: fo.name#获取文件的名称Out[2]: '/bao/file'In [3]: fo.closed#判断文件是否关闭Out[3]: FalseIn [4]: fo.mode#获取文件的访问模式Out[4]: 'wb'In [5]: fo.softspace#判断末尾是否强制加空格Out[5]: 0In [6]: fo.close()#关闭文件In [7]: fo.closed#判断文件是否关闭Out[7]: TrueIn [10]: fo.write('halo')#向文件中追加内容,如果不关闭的话内容还在缓存中,需要关闭文件或者使用flush方法使内容保存到文件中去In [11]: fo.flush()#缓存写入In [12]: fo.tell()#获取文件当前位置Out[12]: 10In [13]: fo.seek(5)#将指针定位到文件的某个位置In [14]: fo.tell()Out[14]: 5In [98]: fo.read()#读取文件的内容,默认读取最大能读取的字节数,并且将操作指针移到最大字节处Out[98]: 'halosdfsdfsdf\nsfdsfsdff\nsdfdsf\naaaaaaaaaaaaddddddddddddddddddsffsdf'In [99]: fo.read(10)#因为上一个操作已经将文件指针移到文件末尾,所以没有剩余内容可以读取Out[99]: ''In [100]: fo.tell()#获取当前文件操作指针的位置Out[100]: 67In [101]: fo.seek(0)#将文件操作指针重新定位到文件开头,然后再去读取就OK了In [102]: fo.read(10)#从文件操作指针出开始读取10个字节的内容Out[102]: 'halosdfsdf'In [109]: cat /bao/filehalosdfsdfsdfsfdsfsdffsdfdsfaaaaaaaaaaaaddddddddddddddddddsffsdfIn [106]: fo.readline()#按行读取文件,再次操作的时候读取下一行,类似生成器Out[106]: 'halosdfsdfsdf\n'In [107]: fo.readline()Out[107]: 'sfdsfsdff\n'In [108]: fo.readline()Out[108]: 'sdfdsf\n'In [109]: fo.readline()Out[109]: 'aaaaaaaaaaaaddddddddddddddddddsffsdf'In [110]: fo.readline()Out[110]: ''In [114]: fo.readlines()#默认一次读取尽可能多的行返回一个列表存储所有的行,每一个行作为一个列表的元素;如果传递一个整形参数的话就读取指定大小的内容后返回,这样可以避免大文件读取造成的内存占用Out[114]: ['halosdfsdfsdf\n', 'sfdsfsdff\n', 'sdfdsf\n', 'aaaaaaaaaaaaddddddddddddddddddsffsdf']In [122]: fo = open('/bao/file')In [123]: p = fo.xreadlines()#获得一个文件读取的迭代对象In [124]: p.next()#调用迭代对象逐个获取文件行In [19]: from collections import IterableIn [20]: isinstance(fo,Iterable)#判断文件对象是可迭代的Out[20]: TrueIn [21]: for i in fo:   ....:     print i   ....:     daemon:x:2:2:daemon:/sbin:/sbin/nologin#with 语句是从 Python 2.5 开始引入的一种与异常处理相关的功能,可以用来安全打开一个文件In [29]: with open('/bao/file','r') as fo:   ....:     print fo.read()   ....:     root:x:0:0:root:/root:/bin/bashbin:x:1:1:bin:/bin:/sbin/nologin

练习

1. 过滤掉文件中以#开头的行:

def fileFilter(fname):    fo = open(fname,'r+')    while True:        line = fo.readlines(2)        if not line:            break        else:            for i in line:                stripLine = i.strip()                if not stripLine.startswith('#'):                    print stripLine    fo.close()

2.根据用户输入的读取行数,然后判断用户的读取行为(继续还是退出)来显示文本中每一次读取的内容:

def fileRead():    while True:        filename = raw_input('Please input file name(q to quit): ')        if filename in 'qQ':            return        try:            fo = open(filename,'r')            lines = raw_input('Please input read lines(q to quit): ')            if lines in 'qQ':                return            try:                lines = int(lines)                print '1-%s lines contents as below:\n'%lines                for i in range(0, lines):                    print fo.readline().strip()                times = 0                while True:                    ynq = raw_input('\nSure to continue read file content[y/n]:')                    if ynq in 'nN':                        return                    if ynq in 'yY':                        if not fo.readline():                            print 'File read to the end!'                            return                        times += 1                        starts = lines * times                        ends = starts + lines                        print '{}-{} lines contents as below:\n'.format(starts + 1, ends)                        for i in range(starts, ends):                            print fo.readline().strip()                fo.close()            except:                print 'Illegal line number!'        except:            print 'No such file or permission denied!'
原创粉丝点击