• Python基础篇【第2篇】: Python文件操作


    Python文件操作

    在Python中一个文件,就是一个操作对象,通过不同属性即可对文件进行各种操作。Python中提供了许多的内置函数和方法能够对文件进行基本操作。

    Python对文件的操作概括来说:1. 打开文件 2.操作文件 3.关闭文件

    1. 打开文件、关闭文件

    Python中使用open函数打开一个文件,创建一个file操作对象。

    open()方法

    语法:

    file object = open(file_name [, access_mode][, buffering])

    各个参数的细节如下:

    • file_name:file_name变量是一个包含了你要访问的文件名称的字符串值。
    • access_mode:access_mode决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。这个参数是非强制的,默认文件访问模式为只读(r)。
    • buffering:如果buffering的值被设为0,就不会有寄存。如果buffering的值取1,访问文件时会寄存行。如果将buffering的值设为大于1的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。

     不同模式打开文件的完全列表:

    一个文件打开后你将得到一个file对象,通过对这个对象的不同属性进行操作,你可以得到有关该文件的各种信息。

    file对象打开后所有属性的列表

    关闭文件

    Close()方法

    File对象的close()方法刷新缓冲区里任何还没写入的信息,并关闭该文件,这之后便不能再进行写入。

    举例:打开关闭文件

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    # 打开一个文件
    fo = open("foo.txt", "wb")
    print "Name of the file: ", fo.name
     
    # 关闭打开的文件
    fo.close()

    结果:

    Name of the file:  foo.txt

    文件操作源码

    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          
    
    file Code
    View Code

    2. 文件操作

    a)read 读操作

    read()方法从一个打开的文件中读取一个字符串。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。一次性将所有文件读取为一个大的字符串。

    语法:

    fileObject.read([count]);

    在这里,被传递的参数是要从已打开文件中读取的字节计数。该方法从文件的开头开始读入,如果没有传入count,它会尝试尽可能多地读取更多的内容,很可能是直到文件的末尾。

    例子:有一个内容如下的文本

    Python is a great language.
    Yeah its great!!
    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    # 打开一个文件
    fo = open("/tmp/foo.txt", "r+")
    str = fo.read(10);
    print "Read String is : ", str
    # 关闭打开的文件
    fo.close()

    b)readline

    readline() 方法用于从文件读取整行,包括 " " 字符。如果指定了一个非负数的参数,则返回指定大小的字节数,包括 " " 字符。每次读取一行,一行一行迭代读取

    语法:

    readline([size]) 方法语法如下:  #size -- 从文件中读取的字节数。

    runoob.txt 的内容如下:

    1:www.runoob.com
    2:www.runoob.com
    3:www.runoob.com
    4:www.runoob.com
    5:www.runoob.com

    读取文件内容

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    # 打开文件
    fo = open("runoob.txt", "rw+")
    print "文件名为: ", fo.name
    
    line = fo.readline()
    print "读取第一行 %s" % (line)
    
    line = fo.readline(5)
    print "读取的字符串为: %s" % (line)
    
    # 关闭文件
    fo.close()

    输出结果

    文件名为:  runoob.txt
    读取第一行 1:www.runoob.com
    
    读取的字符串为: 2:www

    C) readlines

    readlines() 方法用于读取所有行(直到结束符 EOF)并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比sizhint较大, 因为需要填充缓冲区。

    一次读取文件所有内容,以每行一个分隔,形成一个大的列表

    如果碰到结束符 EOF 则返回空字符串。

    语法:

    fileObject.readlines( sizehint );      #sizeint为读取的行数

    返回值

    返回列表,包含所有的行。

    举例:读取上边runoob.txt文本

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    # 打开文件
    fo = open("runoob.txt", "rw+")
    print "文件名为: ", fo.name
    
    line = fo.readlines()
    print "读取的数据为: %s" % (line)
    
    line = fo.readlines(2)
    print "读取的数据为: %s" % (line)
    
    
    # 关闭文件
    fo.close()

    结果:

    文件名为:  runoob.txt
    读取的数据为: ['1:www.runoob.com
    ', '2:www.runoob.com
    ', '3:www.runoob.com
    ', '4:www.runoob.com
    ', '5:www.runoob.com
    ']
    读取的数据为: []

    D) 写操作

    Write()方法可将任何字符串写入一个打开的文件。需要重点注意的是,Python字符串可以是二进制数据,而不是仅仅是文字。

    Write()方法不在字符串的结尾不添加换行符(' '):

    语法:

    fileObject.write(string);    #string代表要写入文件的内容

    举例

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    # 打开一个文件
    fo = open("/tmp/a.txt", "wb")
    fo.write( "Python is a great language.
    Yeah its great!!
    ");
     
    # 关闭打开的文件
    fo.close()

    上述方法会创建foo.txt文件,并将收到的内容写入该文件,并最终关闭文件。如果你打开这个文件,将看到以下内容:

    Python is a great language.
    Yeah its great!!

    E) writelines

    writelines() 方法用于向文件中写入一序列的字符串。这一序列字符串可以是由迭代对象产生的,如一个字符串列表。

    换行需要制定换行符 。

     语法:

    fileObject.writelines( [ str ])    # str为要写入的字符串序列

    该方法没有返回值。

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
    
    # 打开文件
    fo = open("test.txt", "w")
    print "文件名为: ", fo.name
    seq = ["菜鸟教程 1
    ", "菜鸟教程 2"]
    fo.writelines( seq )
    
    # 关闭文件
    fo.close()

    以上实例输出结果为:

    文件名为:  test.txt

    查看文件内容:

    $ cat test.txt 
    菜鸟教程 1
    菜鸟教程 2

    F) 文件位置:

    Tell()方法告诉你文件内的当前位置;换句话说,下一次的读写会发生在文件开头这么多字节之后:

    seek(offset [,from])方法改变当前文件的位置。Offset变量表示要移动的字节数。From变量指定开始移动字节的参考位置。

    如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。

    如果设为1,则使用当前的位置作为参考位置。

    如果它被设为2,那么该文件的末尾将作为参考位置。

    #!/usr/bin/python
    # -*- coding: UTF-8 -*-
     
    # 打开一个文件
    fo = open("/tmp/foo.txt", "r+")
    str = fo.read(10);
    print "Read String is : ", str
     
    # 查找当前位置
    position = fo.tell();
    print "Current file position : ", position
     
    # 把指针再次重新定位到文件开头
    position = fo.seek(0, 0);
    str = fo.read(10);
    print "Again read String is : ", str
    # 关闭打开的文件
    fo.close()

    结果:

    Read String is :  Python is
    Current file position :  10
    Again read String is :  Python is

     G)with

    为了避免打开文件后忘记关闭,可以通过管理上下文,即:
    with open('log','r') as f:

    如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。

    在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:

    with open('log1') as obj1, open('log2') as obj2:
        pass

    线上文件修改举例

      1 #!/usr/bin/env python
      2 # -*- coding:utf-8 -*-
      3 import json
      4 import os
      5 
      6 
      7 def fetch(backend):
      8     backend_title = 'backend %s' % backend
      9     record_list = []
     10     with open('ha') as obj:
     11         flag = False
     12         for line in obj:
     13             line = line.strip()
     14             if line == backend_title:
     15                 flag = True
     16                 continue
     17             if flag and line.startswith('backend'):
     18                 flag = False
     19                 break
     20 
     21             if flag and line:
     22                 record_list.append(line)
     23 
     24     return record_list
     25 
     26 
     27 def add(dict_info):
     28     backend = dict_info.get('backend')
     29     record_list = fetch(backend)
     30     backend_title = "backend %s" % backend
     31     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'])
     32     if not record_list:
     33         record_list.append(backend_title)
     34         record_list.append(current_record)
     35         with open('ha') as read_file, open('ha.new', 'w') as write_file:
     36             flag = False
     37             for line in read_file:
     38                 write_file.write(line)
     39             for i in record_list:
     40                 if i.startswith('backend'):
     41                     write_file.write(i+'
    ')
     42                 else:
     43                     write_file.write("%s%s
    " % (8*" ", i))
     44     else:
     45         record_list.insert(0, backend_title)
     46         if current_record not in record_list:
     47             record_list.append(current_record)
     48 
     49         with open('ha') as read_file, open('ha.new', 'w') as write_file:
     50             flag = False
     51             has_write = False
     52             for line in read_file:
     53                 line_strip = line.strip()
     54                 if line_strip == backend_title:
     55                     flag = True
     56                     continue
     57                 if flag and line_strip.startswith('backend'):
     58                     flag = False
     59                 if not flag:
     60                     write_file.write(line)
     61                 else:
     62                     if not has_write:
     63                         for i in record_list:
     64                             if i.startswith('backend'):
     65                                 write_file.write(i+'
    ')
     66                             else:
     67                                 write_file.write("%s%s
    " % (8*" ", i))
     68                     has_write = True
     69     os.rename('ha','ha.bak')
     70     os.rename('ha.new','ha')
     71 
     72 
     73 def remove(dict_info):
     74     backend = dict_info.get('backend')
     75     record_list = fetch(backend)
     76     backend_title = "backend %s" % backend
     77     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'])
     78     if not record_list:
     79         return
     80     else:
     81         if current_record not in record_list:
     82             return
     83         else:
     84             del record_list[record_list.index(current_record)]
     85             if len(record_list) > 0:
     86                 record_list.insert(0, backend_title)
     87         with open('ha') as read_file, open('ha.new', 'w') as write_file:
     88             flag = False
     89             has_write = False
     90             for line in read_file:
     91                 line_strip = line.strip()
     92                 if line_strip == backend_title:
     93                     flag = True
     94                     continue
     95                 if flag and line_strip.startswith('backend'):
     96                     flag = False
     97                 if not flag:
     98                     write_file.write(line)
     99                 else:
    100                     if not has_write:
    101                         for i in record_list:
    102                             if i.startswith('backend'):
    103                                 write_file.write(i+'
    ')
    104                             else:
    105                                 write_file.write("%s%s
    " % (8*" ", i))
    106                     has_write = True
    107     os.rename('ha','ha.bak')
    108     os.rename('ha.new','ha')
    109 
    110 if __name__ == '__main__':
    111     """
    112     print '1、获取;2、添加;3、删除'
    113     num = raw_input('请输入序号:')
    114     data = raw_input('请输入内容:')
    115     if num == '1':
    116         fetch(data)
    117     else:
    118         dict_data = json.loads(data)
    119         if num == '2':
    120             add(dict_data)
    121         elif num == '3':
    122             remove(dict_data)
    123         else:
    124             pass
    125     """
    126     #data = "www.oldboy.org"
    127     #fetch(data)
    128     #data = '{"backend": "tettst.oldboy.org","record":{"server": "100.1.7.90","weight": 20,"maxconn": 30}}'
    129     #dict_data = json.loads(data)
    130     #add(dict_data)
    131     #remove(dict_data)
    132 
    133 demo
    View Code
     
  • 相关阅读:
    微信小程序 checkbox 组件
    微信小程序 button 组件
    h5视频标签 video
    h5离线缓存
    ECharts插件介绍(图表库)
    rich-text 副文本组件 text文本组件
    progress组件(进度条)
    icon组件
    movable-view组件
    android 双击图片变大,缩放功能
  • 原文地址:https://www.cnblogs.com/sunailong/p/5163752.html
Copyright © 2020-2023  润新知