Python之路【第三篇】:文件操作

  • Post author:
  • Post category:python


一、文件操作步骤

  1. 打开文件,得到文件句柄并赋值给一个变量
  2. 通过句柄对文件进行操作
  3. 关闭文件

歌名:《大火》
演唱:李佳薇
作词:姚若龙
作曲:马奕强
歌词:
有座巨大的停了的时钟
倾倒在赶路的途中 挡我 向前走
有只黑色的老鹰在俯冲
叼走了你送的承诺 回头 冷冷看我
有阵将眼泪扫落的狂风
掀起了隐藏的疼痛 把我 变赤裸
我为蔓延的回忆除草了
心中却长出盛开的 寂寞 原来是梦
有些伤痕像场大火 把心烧焦难以复活
不碰了好像忘了 恐惧却在脑海住着
重复卡在一个 重要的时刻 不自觉就会退缩
连幸福也克制着 觉得什麽都会变的
防备着平静到最後 连爱也透着冷漠
有人说我的微笑是暖的
心里却很难被感动 狠狠 解剖我
从不是有意想害谁难过
甚至会沮丧一直没突破 沉重的壳
有些伤痕像场大火 把心烧焦难以复活
不碰了好像忘了 恐惧却在脑海住着
重复卡在一个 重要的时刻 不自觉就会退缩
连幸福也克制着 觉得什麽都会变的
防备着平静到最後 独自寂寞
有些伤痕像场大火 把心烧焦难以复活
可是我 想要忘了 恐惧如何把我上锁
期待阳光炽热 爱来的时刻 能用力去拥抱着
多幸福就多快乐 不让未知成为负荷
投入的留下了每一刻 不怕的人 最富有
人太脆弱 会不停错过
太多宝贵的 都需要跋涉 才可以获得
太多璀璨的 越隔着夜色 越光芒四射


示范文件内容

二、文件操作详解

操作文件时,一般需要经历如下步骤:

  • 打开文件
  • 操作文件
  • 关闭文件

1. 打开或关闭文件

open 函数

你必须先用Python内置的open()函数打开一个文件,创建一个file对象,相关的方法才可以调用它进行读写。

语法:

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

各个参数的细节如下:

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


注:


python中打开文件有两种方式,即:open(…) 和  file(…) ,本质上前者在内部会调用后者来进行文件操作,

推荐使用 open


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

打开文件的模式有:

  • r ,只读模式【默认模式,文件必须存在,不存在则抛出异常】
  • w,只写模式【不可读;不存在则创建;存在则清空内容】
  • x, 只写模式【不可读;不存在则创建,存在则报错】
  • a, 追加模式【可读;   不存在则创建;存在则只追加内容】

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

  • r+, 读写【可读,可写】
  • w+,写读【可读,可写】
  • x+ ,写读【可读,可写】
  • a+, 写读【可读,可写】

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

  • rU
  • r+U

“b”表示以字节的方式操作

  • rb  或 r+b
  • wb 或 w+b
  • xb 或 w+b
  • ab 或 a+b


注:

以b方式打开时,读取到的内容是字节类型,写入时也需要提供字节类型,不能指定编码。

2. File对象的属性

一个文件被打开后,你有一个file对象,你可以得到有关该文件的各种信息。

以下是和file对象相关的所有属性的列表:

file.closed 返回true如果文件已被关闭,否则返回false。
file.mode 返回被打开文件的访问模式。
file.name 返回文件的名称。
file.softspace 如果用print输出后,必须跟一个空格符,则返回false。否则返回true。

如下实例:

#!/usr/bin/python
# -*- coding: UTF-8 -*-
 
# 打开一个文件
fo = open("foo.txt", "wb")
print "文件名: ", fo.name
print "是否已关闭 : ", fo.closed
print "访问模式 : ", fo.mode
print "末尾是否强制加空格 : ", fo.softspace

3. 文件操作函数

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

3.1 file(文件方法)

  • 以下是文件操作的常用方法
1


file.close()

关闭文件。关闭后文件不能再进行读写操作。

2


file.flush()

刷新文件内部缓冲,直接把内部缓冲区的数据立刻写入文件, 而不是被动的等待输出缓冲区写入。

3


file.fileno()

返回一个整型的文件描述符(file descriptor FD 整型), 可以用在如os模块的read方法等一些底层操作上。

4


file.isatty()

如果文件连接到一个终端设备返回 True,否则返回 False。

5


file.next()


返回文件下一行。

6


file.read([size])


从文件读取指定的字节数,如果未给定或为负则读取所有。

7


file.readline([size])


读取整行,包括 “\n” 字符。

8


file.readlines([sizeint])


读取所有行并返回列表,若给定sizeint>0,返回总和大约为sizeint字节的行, 实际读取值可能比 sizeint 较大, 因为需要填充缓冲区。

9


file.seek(offset[, whence])

设置文件当前位置

10


file.tell()

返回文件当前位置。

11


file.truncate([size])

截取文件,截取的字节通过size指定,默认为当前文件位置。

12


file.write(str

)    将字符串写入文件,没有返回值。

13


file.writelines(sequence)

向文件写入一个序列字符串列表,如果需要换行则要自己加入每行的换行符。

3.2 文件内置函数flush

flush原理:

  1. 文件操作是通过软件将文件从硬盘读到内存。
  2. 写入文件的操作也都是存入内存缓冲区buffer(内存速度快于硬盘,如果写入文件的数据都从内存刷到硬盘,内存与硬盘的速度延迟会被无限放大,效率变低,所以要刷到硬盘的数据我们统一往内存的一小块空间即buffer中放,一段时间后操作系统会将buffer中数据一次性刷到硬盘)
  3. flush即,强制将写入的数据刷到硬盘。

滚动条:

import sys,time

for i in  range(10):
    sys.stdout.write('#')
    sys.stdout.flush()
    time.sleep(0.2)

3.3 文件光标移动

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

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

如果from被设为0,这意味着将文件的开头作为移动字节的参考位置。如果设为1,则使用当前的位置作为参考位置。如果它被设为2,那么该文件的末尾将作为参考位置。

seek():移动文件读取指针到指定位置,设置文件当前位置。

tell():返回文件读取指针的位置。

seek()的三种模式:

(1)f.seek(p,0)  移动当文件第p个字节处,绝对位置

(2)f.seek(p,1)  移动到相对于当前位置之后的p个字节

(3)f.seek(p,2)  移动到相对文章尾之后的p个字节

例子:

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


注:

read(3)代表读取3个字符,其余的文件内光标移动都是以字节为单位如seek,tell,read,truncate

3.4 open函数详解


1. open()语法


open(file[, mode[, buffering[, encoding[, errors[, newline[, closefd=True]]]]]])

open函数有很多的参数,常用的是file,mode和encoding


file

文件位置,需要加引号


mode

文件打开模式,见下面3


buffering

的可取值有0,1,>1三个,0代表buffer关闭(只适用于二进制模式),1代表line buffer(只适用于文本模式),>1表示初始化的buffer大小;


encoding

表示的是返回的数据采用何种编码,一般采用utf8或者gbk;


errors

的取值一般有strict,ignore,当取strict的时候,字符编码出现问题的时候,会报错,当取ignore的时候,编码出现问题,程序会忽略而过,继续执行下面的程序。


newline

可以取的值有None, \n, \r, ”, ‘\r\n’,用于区分换行符,但是这个参数只对文本模式有效;


closefd

的取值,是与传入的文件参数有关,默认情况下为True,传入的file参数为文件的文件名,取值为False的时候,file只能是文件描述符,什么是文件描述符,就是一个非负整数,在Unix内核的系统中,打开一个文件,便会返回一个文件描述符。


2.

Python中file()与open()区别


两者都能够打开文件,对文件进行操作,也具有相似的用法和参数,但是,这两种文件打开方式有本质的区别,

file为文件类

,用file()来打开文件,相当于这是在构造文件类,而用open()打开文件,是用python的内建函数来操作,

建议使用open


3. 参数mode的基本取值

Character Meaning

‘r’
open for reading (default)

‘w’
open for writing, truncating the file first

‘a’
open for writing, appending to the end of the file if it exists

‘b’
binary mode

‘t’
text mode (default)

‘+’
open a disk file for updating (reading and writing)

‘U’
universal newline mode (for backwards compatibility; should not be used in new code)

r、w、a为打开文件的基本模式,对应着只读、只写、追加模式;

b、t、+、U这四个字符,与以上的文件打开模式组合使用,二进制模式,文本模式,读写模式、通用换行符,根据实际情况组合使用;

r 以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
rb 以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。
r+ 打开一个文件用于读写。文件指针将会放在文件的开头。
rb+ 以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。
w 打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb 以二进制格式打开一个文件只用于写入。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
w+ 打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
wb+ 以二进制格式打开一个文件用于读写。如果该文件已存在则将其覆盖。如果该文件不存在,创建新文件。
a 打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
ab 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
a+ 打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
ab+ 以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写。

4. 常见的mode取值组合

r或rt 默认模式,文本模式读
rb   二进制文件
    
w或wt 文本模式写,打开前文件存储被清空
wb  二进制写,文件存储同样被清空
    
a  追加模式,只能写在文件末尾
a+ 可读写模式,写只能写在文件末尾
    
w+ 可读写,与a+的区别是要清空文件内容
r+ 可读写,与a+的区别是可以写到文件任何位置


3.5 上下文管理

with open('a.txt','w') as f:          # 如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。
   pass

with open('a.txt','r') as read_f,open('b.txt','w') as write_f:     #在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:
    data=read_f.read()
    write_f.write(data)

3.6 模拟tail -f命令 功能

import time
with open('access.log','r',encoding='utf-8') as f:
    f.seek(0,2)          # 打开文件后立刻将光标移动至文件末尾
    while True:
        line=f.readline().strip()
        if line:
            print('新增一行日志',line)
        time.sleep(0.5)           

3.7

文件的修改

import os
with open('a.txt','r',encoding='utf-8') as read_f,\
        open('.a.txt.swap','w',encoding='utf-8') as write_f:
    for line in read_f:
        if line.startswith('hello'):
            line='哈哈哈\n'
        write_f.write(line)

os.remove('a.txt')
os.rename('.a.txt.swap','a.txt')

那么问题来了…

1、如何在线上环境优雅的修改配置文件?


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 oldboy.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.oldboy.org
        server 100.1.7.9 100.1.7.9 weight 20 maxconn 3000

原配置文件


原配置文件


1、查
    输入:www.oldboy.org
    获取当前backend下的所有记录

2、新建
    输入:
        arg = {
            'bakend': 'www.oldboy.org',
            'record':{
                'server': '100.1.7.9',
                'weight': 20,
                'maxconn': 30
            }
        }

3、删除
    输入:
        arg = {
            'bakend': 'www.oldboy.org',
            'record':{
                'server': '100.1.7.9',
                'weight': 20,
                'maxconn': 30
            }
        }

需求


需求


#!/usr/bin/env python
# -*- coding:utf-8 -*-
import os

def query(content):
    '''
    功能: 根据用户传入的域名查找相关的配置信息,返回一个列表
    :param content: 用户输入的域名
    :return: data
    '''
    res_list = []
    content = 'backend %s' % content
    with open('haproxy.conf', 'r', encoding='utf-8') as fo:
        flag = False
        for line in fo:
            line = line.strip()
            if line.startswith('backend') and content == line:
                flag = True
                continue
            if flag:
                res_list.append(line)
                flag = False
                continue
        return res_list

def add(content):
    '''
    功能: 获取用户输入内容并写入文件
    :param content:
    :return:
    '''
    # 用于存放写入文件内容的列表
    data_list = []
    data_dic = eval(content)
    # print('转化为字典: ', data_dic)
    backend = data_dic.get('backend')
    server = data_dic.get('record')
    server_con = "server {} {} weight {} maxconn {}".format(server['server'], server['server'], server['weight'],
                                                            server['maxconn'])
    query_list = query(backend)
    if server_con in query_list:
        print('\033[1;31m内容已存在!\033[0m')
    else:
        ele = 'backend %s' % backend
        data_list.append(ele)
        data_list.append(server_con)
        with open('haproxy.conf','a+',encoding='utf-8') as fo:
            for item in data_list:
                if item.strip().startswith('backend'):
                    fo.write('\n')
                    fo.write("\n%s\n" % item)
                else:
                    fo.write('\t\t%s' % item)
            print('\033[1;32m写入成功!\033[0m')

def remove(content):
    """
    功能: 查找到用户输入的内容并删除
    :param content:
    :return:
    """
    data_dic = eval(content)
    backend_con = data_dic.get('backend')
    server_dic = data_dic.get('record')
    data = "server {} {} weight {} maxconn {}".format(server_dic['server'], server_dic['server'],
                                                      server_dic['weight'], server_dic['maxconn'])
    match = "backend %s" % backend_con
    data_list = query(backend_con)
    # print("query: ", data_list)
    if not data_list or data not in data_list:
        print("\033[1;31m内容不存在!\033[0m")
        return
    elif data in data_list:
        flag = False
        with open('haproxy.conf', encoding='utf-8') as read_f, open('ha.swap', 'w', encoding='utf-8') as write_f:
            for line in read_f:
                line = line.strip()
                if line.startswith('backend') and match == line:
                    flag = True
                    continue
                if flag and data == line:
                    flag = False
                    continue
                elif flag and data != line:
                    flag = False
                    write_f.write('%s\n' % match)
                if not flag:
                    write_f.write('%s\n' % line)
            print('删除成功!')
    os.rename("haproxy.conf","haproxy.conf_bak")
    os.rename("ha.swap","haproxy.conf")


if __name__ == '__main__':
    info = """
    1. 查询
    2. 增加
    3. 删除
    4. 退出
    """
    print(info)
    menu_dic = {
        '1': query,
        '2': add,
        '3': remove,
        '4': exit
    }
    while True:
        choice = input("请选择您需要操作的id: ").strip()
        if not choice or choice not in menu_dic: continue
        if choice == '4': break
        content = input("请输入内容: ").strip()
        # content = "{'backend': 'www.oldboy.org','record':{'server': '100.1.7.9','weight': 20,'maxconn': 300}}"
        # content = "www.oldboy.org"
        if choice == '1':
            res_list = menu_dic[choice](content)  # 用choice作为key,从字典中获取到对应的函数对象后加(),即调用函数,将content作为参数传入函数
            if res_list:
                print("\033[1;32m查询的结果为:\033[0m %s" % res_list)
            else:
                print("\033[1;31m未查找到内容\033[0m")
        else:
            menu_dic[choice](content)


demo

详细参考:

http://www.runoob.com/python/python-files-io.html

转载于:https://www.cnblogs.com/aslongas/p/6785698.html