• python基础_文件操作


    文件操作一般包含以下内容: 

      1、打开文件

      2、操作文件

      3、关闭文件

    一、打开文件:

          一般打开文件使用的是: file('路径','权限')和open('路径','权限') 两种方式,推荐是用open,因为: 

              1、open也是调用源码里的file方法,但有时版本不同或升级了,源码的file位置变动了,自己写的代码也需改变相应的位置,

         而直接调用open的话,它会自己寻找file方法,不需我们改变。

         2、open里面还集成了许多方法,其中包括文件打开时适配文件类型来打开,如txt文件则使用文件阅读器来打开。

          

    打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文件操作。

    打开文件的模式有:

    • r,只读模式(默认)。
    • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
    • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

    "+" 表示可以同时读写某个文件

    • r+,可读写文件。【可读;可写;可追加】
    • w+,写读
    • a+,同a

    "U"表示在读取时,可以将 自动转换成 (与 r 或 r+ 模式同使用)

    • rU
    • r+U

    "b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

    • rb
    • wb
    • ab

    如: 

        obj = open('log','r')  #以只读方式打开文件log.

        obj.seek(5)    #定义开始时游标所在位置

      print obj.tell()   #打印(查询)此时游标所在位置

        print obj.read()  #读取文件内容

        print obj.tell()

        obj.close()     #关闭文件

       

     file的源码:   

    class file(object):
      
        def close(self): # real signature unknown; restored from __doc__
            关闭文件
            """
            close() -> None or (perhaps) an integer.  Close the file.
             
            Sets data attribute .closed to True.  A closed file cannot be used for
            further I/O operations.  close() may be called more than once without
            error.  Some kinds of file objects (for example, opened by popen())
            may return an exit status upon closing.
            """
     
        def fileno(self): # real signature unknown; restored from __doc__
            文件描述符  
             """
            fileno() -> integer "file descriptor".
             
            This is needed for lower-level file interfaces, such os.read().
            """
            return 0    
     
        def flush(self): # real signature unknown; restored from __doc__
            刷新文件内部缓冲区
            """ flush() -> None.  Flush the internal I/O buffer. """
            pass
     
     
        def isatty(self): # real signature unknown; restored from __doc__
            判断文件是否是同意tty设备
            """ isatty() -> true or false.  True if the file is connected to a tty device. """
            return False
     
     
        def next(self): # real signature unknown; restored from __doc__
            获取下一行数据,不存在,则报错
            """ x.next() -> the next value, or raise StopIteration """
            pass
     
        def read(self, size=None): # real signature unknown; restored from __doc__
            读取指定字节数据
            """
            read([size]) -> read at most size bytes, returned as a string.
             
            If the size argument is negative or omitted, read until EOF is reached.
            Notice that when in non-blocking mode, less data than what was requested
            may be returned, even if no size parameter was given.
            """
            pass
     
        def readinto(self): # real signature unknown; restored from __doc__
            读取到缓冲区,不要用,将被遗弃
            """ readinto() -> Undocumented.  Don't use this; it may go away. """
            pass
     
        def readline(self, size=None): # real signature unknown; restored from __doc__
            仅读取一行数据
            """
            readline([size]) -> next line from the file, as a string.
             
            Retain newline.  A non-negative size argument limits the maximum
            number of bytes to return (an incomplete line may be returned then).
            Return an empty string at EOF.
            """
            pass
     
        def readlines(self, size=None): # real signature unknown; restored from __doc__
            读取所有数据,并根据换行保存值列表
            """
            readlines([size]) -> list of strings, each a line from the file.
             
            Call readline() repeatedly and return a list of the lines so read.
            The optional size argument, if given, is an approximate bound on the
            total number of bytes in the lines returned.
            """
            return []
     
        def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
            指定文件中指针位置
            """
            seek(offset[, whence]) -> None.  Move to new file position.
             
            Argument offset is a byte count.  Optional argument whence defaults to
            0 (offset from start of file, offset should be >= 0); other values are 1
            (move relative to current position, positive or negative), and 2 (move
            relative to end of file, usually negative, although many platforms allow
            seeking beyond the end of a file).  If the file is opened in text mode,
            only offsets returned by tell() are legal.  Use of other offsets causes
            undefined behavior.
            Note that not all file objects are seekable.
            """
            pass
     
        def tell(self): # real signature unknown; restored from __doc__
            获取当前指针位置
            """ tell() -> current file position, an integer (may be a long integer). """
            pass
     
        def truncate(self, size=None): # real signature unknown; restored from __doc__
            截断数据,仅保留指定之前数据
            """
            truncate([size]) -> None.  Truncate the file to at most size bytes.
             
            Size defaults to the current file position, as returned by tell().
            """
            pass
     
        def write(self, p_str): # real signature unknown; restored from __doc__
            写内容
            """
            write(str) -> None.  Write string str to file.
             
            Note that due to buffering, flush() or close() may be needed before
            the file on disk reflects the data written.
            """
            pass
     
        def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
            将一个字符串列表写入文件
            """
            writelines(sequence_of_strings) -> None.  Write the strings to the file.
             
            Note that newlines are not added.  The sequence can be any iterable object
            producing strings. This is equivalent to calling write() for each string.
            """
            pass
     
        def xreadlines(self): # real signature unknown; restored from __doc__
            可用于逐行读取文件,非全部
            """
            xreadlines() -> returns self.
             
            For backward compatibility. File objects now include the performance
            optimizations previously implemented in the xreadlines module.
            """
            pass
    View Code

    with的使用: 

    #-*- coding:utf-8 -*-

    #使用with可允许两个文件操作,且它会自动释放文件
    with open('log','r') as obj1,open('log2','w') as obj2:  
    for line in obj1:
    new_line = line.replace('231','nice')
    obj2.write(new_line)

    以上代码实现了log文件复制到log2并把内容替换。
    log:
    kobe|123|1
    jeams|231|2
    pual|435|3

    log2:
    kobe|123|1
    jeams|nice|2
    pual|435|3

    该功能可运用在文件修改上



    文件操作实战:
    需求:操作conf配置文件,具有查询、添加、删除功能!
    原配置文件:
    global
            log 127.0.0.1 local2
            daemon
            maxconn 256
            log 127.0.0.1 local2 info
    defaults
            log global
            mode http
            timeout connect 5000ms
            timeout client 50000ms
            timeout server 50000ms
            option  dontlognull
    
    listen stats :8888
            stats enable
            stats uri       /admin
            stats auth      admin:1234
    
    frontend nba.org
            bind 0.0.0.0:80
            option httplog
            option httpclose
            option  forwardfor
            log global
            acl www hdr_reg(host) -i www.oldboy.org
            use_backend www.oldboy.org if www
    
    backend www.nba.org
            server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
            server 100.1.7.66 100.1.7.9 weight 20 maxconn 3000
    
    backend china.nba.org
            server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000
            server 100.1.7.66 100.1.7.9 weight 20 maxconn 3000
    View Code

     需求:

    1、查
        输入:www.nba.org
        获取当前backend下的所有记录
    
    2、新建
        输入:
            arg = {
                'bakend': 'www.nba.org',
                'record':{
                    'server': '100.1.7.9',
                    'weight': 20,
                    'maxconn': 30
                }
            }
    
    3、删除
        输入:
            arg = {
                'bakend': 'www.nba.org',
                'record':{
                    'server': '100.1.7.9',
                    'weight': 20,
                    'maxconn': 30
                }
            }
    
    需求
    View Code

    demo:

    #-*- coding:utf-8 -*-
    
    import json
    import os
    
    def fetch(kk):
        fetch_list = []
        with open('conf') as obj:
            flag = False
            for line in obj:
                #读取每一行
                if line.strip() == 'backend %s' % (kk): #判断是否符合输入内容
                    flag = True
                    continue     #继续,结束该次循环,从下次循环开始
                if flag and line.strip().startswith('backend'):
                    break       #获取内容完后遇到下次backend停止循环
                if flag and line.strip():
                    fetch_list.append(line.strip())   #获取内容
    
        #print fetch_list
        return fetch_list
    
    #print fetch('www.oldboy.org')
    
    def add_data(dict_info):
        backend_str = dict_info.get('backend')
        record_list = fetch(backend_str)
        backend_title = 'backend %s'% backend_str
        current_record = 'server %s %s weight %d maxconn %d' % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn'])
        if record_list: #为true,说明原文件有backend的标题
            record_list.insert(0, backend_title)  #添加backend内容至读取原文件是否含添加内容的列表里
            if current_record not in record_list:  #内容不存在,则添加进取
                record_list.append(current_record)
    
            with open('conf','r') as read_file, open('conf.new', 'w') as write_file:
                flag = False
                has_write = False
                for line in read_file:
                    line_strip = line.strip()
                    if line_strip == backend_title:  #到backend标题行,不用将backend写进添加文件里,再把flag写true以便下面执
                    # 行else语句里添加backend及新增内容
                        flag = True
                        continue
                    if flag and line_strip.startswith('backend'):  #碰到下个backend,就停止else的新添的backend部分内容的添加
                        flag = False
                    if not flag:
                        write_file.write(line)    #该步骤是其他非新增backend部分的内容添加
                    else:   #把新增backend的内容写进文件
                        if not has_write:  #用标记位来控制内容不循环多次重复添加
                            for i in record_list:
                                if i.startswith('backend'):
                                    write_file.write(i+'
    ')
                                else:
                                    write_file.write("%s%s
    " % (8*" ", i))
                        has_write = True
    
        else:      #原文件没有内容
            record_list.append(backend_title)
            record_list.append(current_record)
            with open('conf','r') as read_file, open('conf.new', 'w') as write_file:
                flag = False
                for line in read_file:
                    write_file.write(line)
                for i in record_list:
                    if i.startswith('backend'):
                        write_file.write(i+'
    ')
                    else:
                        write_file.write("%s%s
    
    " % (8*" ", i))
                        
        #os.rename('conf','conf.bak')  #替换文件,注意该rename功能在linux上执行没问题,windows下不支持使用
        #os.rename('conf.new','conf')
    
    
    def del_data(dict_info):
        backend_str = dict_info.get('backend')
        record_list = fetch(backend_str)
        backend_title = 'backend %s'% backend_str
        current_record = 'server %s %s weight %d maxconn %d' % (dict_info['record']['server'], dict_info['record']['server'], dict_info['record']['weight'], dict_info['record']['maxconn'])
        if not record_list:  #不存在需删除的backend内容
            return     #直接返回
        else:   #存在需删除内容的标题backend
            if current_record not in record_list:  #不存在需删除的记录
                return
            else:     #存在需删除的记录
                del record_list[record_list.index(current_record)]  #以匹配内容条目为列表节点,进行删除
                print 'Delete content of ("%s") was succeed!' % current_record
                if len(record_list) > 0:   #判断删除后是否还有其他内容,有则添加backend标题
                    record_list.insert(0, backend_title)
            with open('conf','r') as read_file, open('conf.new', 'w') as write_file:  #以下功能为有匹配写入新文件,和添加一样逻辑
                flag = False
                has_write = False
                for line in read_file:
                    line_strip = line.strip()
                    if line_strip == backend_title:
                        flag = True
                        continue
                    if flag and line_strip.startswith('backend'):
                        flag = False
                    if not flag:
                        write_file.write(line)
                    else:
                        if not has_write:
                            for i in record_list:
                                if i.startswith('backend'):
                                    write_file.write(i+'
    ')
                                else:
                                    write_file.write("%s%s
    " % (8*" ", i))
                        has_write = True
    
        #os.rename('conf','conf.bak')  #替换文件,注意该rename功能在linux上执行没问题,windows下不支持使用
        #os.rename('conf.new','conf')
    
    
    
    if __name__ == '__main__':
    
        print u'1、获取;2、添加;3、删除'
        num = raw_input(u'请输入序号:')
        data = raw_input(u'请输入内容:')
        if num == '1':
            srech_data = fetch(data)
            print srech_data
        else:
            dict_data = json.loads(data)
            if num == '2':
                add_data(dict_data)
            elif num == '3':
                del_data(dict_data)
            else:
                pass
    
    '''
    data = '{"backend": "china.nba.org","record":{"server": "100.1.7.99","weight": 20,"maxconn": 3000}}'
    dict_data = json.loads(data)
    
    del_data(dict_data)
    
    
    '''
    View Code

    总结:文件操作上主要注意一些权限、空格、、换行,读写进以列表或字典方式保存以及编码等问题。

    
    
  • 相关阅读:
    SpringMvc 框架
    面试:你最大的长处和弱点分别是什么?这些长处和弱点对你在企业的业绩会有什么样的影响?
    线程、并发、并行、进程是什么,以及如何开启新的线程?
    面向对象三大特性
    一台客户端有三百个客户与三百个客户端有三百个客户对服务器施压,有什么区别?
    JavaScript 引擎
    Spring Data JPA简介 Spring Data JPA特点
    博主博客
    微信相关
    关于正则表达式
  • 原文地址:https://www.cnblogs.com/fengzaoye/p/5715900.html
Copyright © 2020-2023  润新知