博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python 文件操作与函数式编程
阅读量:7080 次
发布时间:2019-06-28

本文共 9906 字,大约阅读时间需要 33 分钟。

hot3.png

内置函数

文件操作

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

  • 打开文件

  • 操作文件

一、打开文件

文件句柄 = file('文件路径''模式')

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

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

打开文件的模式有:

  • r,只读模式(默认)。

  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】

  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

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

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

  • w+,无意义

  • a+,同a

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

  • rU

  • r+U

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

  • rb

  • wb

  • ab

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

三、with

为了避免打开文件后忘记关闭,可以通过管理上下文,即:

with open('log','r') as f:         ...如此方式,当with代码块执行完毕时,内部会自动关闭并释放文件资源。在Python 2.7 后,with又支持同时对多个文件的上下文进行管理,即:with open('log1') as obj1, open('log2') as obj2:    pass四、那么问题来了...1、如何在线上环境优雅的修改配置文件?    global               log 127.0.0.1 local2        daemon        maxconn 256        log 127.0.0.1 local2 infodefaults        log global        mode http        timeout connect 5000ms        timeout client 50000ms        timeout server 50000ms        option  dontlognulllisten stats :8888        stats enable        stats uri       /admin        stats auth      admin:1234frontend eddy.org        bind 0.0.0.0:80        option httplog        option httpclose        option  forwardfor        log global        acl www hdr_reg(host) -i www.oschina.org        use_backend www.oschina.org if wwwbackend www.oschina.org        server 1.1.1.1 weight 20 maxconn 3000原配置文件1、查    输入:www.oschina.org    获取当前backend下的所有记录2、新建    输入:        arg = {            'bakend': 'www.oschina.org',            'record':{                'server': '2.2.2.2',                'weight': 20,                'maxconn': 30            }        }3、删除    输入:        arg = {            'bakend': 'www.oschina.org',            'record':{                'server': '2.2.2.2',                'weight': 20,                'maxconn': 30            }        }需求

2、文件处理中xreadlines的内部是如何实现的呢?

        read会读取所有内容到内存

        xreadlines则只有在循环迭代时才获取

        

def NReadlines():    with open('log','r') as f:        while True:            line = f.next()            if line:                yield line            else:                returnfor i in NReadlines():    print i基于next自定义生成器NReadlinesdef NReadlines():    with open('log','r') as f:        seek = 0        while True:            f.seek(seek)            data = f.readline()            if data:                seek = f.tell()                yield data            else:                returnfor item in NReadlines():    print item基于seek和tell自定义生成器NReadlines

在学习函数之前,一直遵循:面向过程编程,即:根据业务逻辑从上到下实现功能,其往往用一长段代码来实现指定功能,开发过程中最常见的操作就是粘贴复制,也就是将之前实现的代码块复制到现需功能处,如下

while 
True
    
if 
cpu利用率 > 
90
%
:
        
#发送邮件提醒
        
连接邮箱服务器
        
发送邮件
        
关闭连接
  
    
if 
硬盘使用空间 > 
90
%
:
        
#发送邮件提醒
        
连接邮箱服务器
        
发送邮件
        
关闭连接
  
    
if 
内存占用 > 
80
%
:
        
#发送邮件提醒
        
连接邮箱服务器
        
发送邮件
        
关闭连接

if条件语句下的内容可以被提取出来公用

def 
发送邮件(内容)
    
#发送邮件提醒
    
连接邮箱服务器
    
发送邮件
    
关闭连接
  
while 
True
  
    
if 
cpu利用率 > 
90
%
:
        
发送邮件(
'CPU报警'
)
  
    
if 
硬盘使用空间 > 
90
%
:
        
发送邮件(
'硬盘报警'
)
  
    
if 
内存占用 > 
80
%
:

对于上述的两种实现方式,第二次必然比第一次的重用性和可读性要好,其实这就是函数式编程和面向过程编程的区别:

  • 函数式:将某功能代码封装到函数中,日后便无需重复编写,仅调用函数即可

  • 面向对象:对函数进行分类和封装,让开发“更快更好更强...”

函数的定义主要有如下要点:

  • def:表示函数的关键字

  • 函数名:函数的名称,日后根据函数名调用函数

  • 函数体:函数中进行一系列的逻辑计算,如:发送邮件、计算出 [11,22,38,888,2]中的最大数等...

  • 参数:为函数体提供数据

  • 返回值:当函数执行完毕后,可以给调用者返回数据。

以上要点中,比较重要有参数和返回值:

1、返回值

函数是一个功能块,该功能到底执行成功与否,需要通过返回值来告知调用者。

def 发送短信():         发送短信的代码...     if 发送成功:        return True    else:        return False  while True:         # 每次执行发送短信函数,都会将返回值自动赋值给result    # 之后,可以根据result来写日志,或重发等操作     result = 发送短信()    if result == False:        记录日志,短信发送失败...

2、参数

def CPU报警邮件()    #发送邮件提醒    连接邮箱服务器    发送邮件    关闭连接def 硬盘报警邮件()    #发送邮件提醒    连接邮箱服务器    发送邮件    关闭连接def 内存报警邮件()    #发送邮件提醒    连接邮箱服务器    发送邮件    关闭连接 while True:     if cpu利用率 > 90%:        CPU报警邮件()     if 硬盘使用空间 > 90%:        硬盘报警邮件()     if 内存占用 > 80%:        内存报警邮件()上例,无参数实现def 发送邮件(邮件内容)    #发送邮件提醒    连接邮箱服务器    发送邮件    关闭连接 while True:     if cpu利用率 > 90%:        发送邮件("CPU报警了。")     if 硬盘使用空间 > 90%:        发送邮件("硬盘报警了。")     if 内存占用 > 80%:        发送邮件("内存报警了。")上列,有参数实现

函数的有三中不同的参数:

  • 普通参数

  • 默认参数

  • 动态参数

# ######### 定义函数 ######### # name 叫做函数func的形式参数,简称:形参def func(name):    print name# ######### 执行函数 ######### #  'eddy' 叫做函数func的实际参数,简称:实参func('eddy')普通参数def func(name, age = 18):        print "%s:%s" %(name,age)# 指定参数func('eddy', 19)# 使用默认参数func('eddy')注:默认参数需要放在参数列表最后默认参数def func(*args):    print args# 执行方式一func(11,33,4,4454,5)# 执行方式二li = [11,2,2,3,3,4,54]func(*li)动态参数一def func(**kwargs):    print args# 执行方式一func(name='eddy',age=18)# 执行方式二li = {'name':'eddy', age:18, 'gender':'male'}func(**li)动态参数二def func(*args, **kwargs):        print args        print kwargs    扩展import smtplibfrom email.mime.text import MIMETextfrom email.utils import formataddr  msg = MIMEText('邮件内容', 'plain', 'utf-8')msg['From'] = formataddr(["eddy",'eddy@126.com'])msg['To'] = formataddr(["yys",'yys@qq.com'])msg['Subject'] = "主题" server = smtplib.SMTP("smtp.126.com", 25)server.login("eddy@126.com", "邮箱密码")server.sendmail('eddy@126.com', ['yys@qq.com',], msg.as_string())server.quit()

转载于:https://my.oschina.net/eddylinux/blog/527739

你可能感兴趣的文章
pyton全栈开发从入门到放弃之数据类型与变量
查看>>
nessus 插件更新
查看>>
Teradata基础教程中的数据库试验环境脚本
查看>>
html+css
查看>>
cocos2d-x 数据存储
查看>>
iproute2
查看>>
js对数组的操作
查看>>
python 安装surprise库解决 c++tools错误问题
查看>>
java 练习题
查看>>
【题解】【排列组合】【回溯】【Leetcode】Generate Parentheses
查看>>
spring注解第07课 @Valid和@Validated的总结区分
查看>>
使用apache自带的压力测试工具
查看>>
PAT 1090 Highest Price in Supply Chain[较简单]
查看>>
手机web——自适应网页设计
查看>>
away3d 4.1 alpha 教程 换装篇 <3> 人物动态换装DEMO
查看>>
《你必须知道的.NET》--is和as(Ⅰ)
查看>>
VueJs组件prop验证简单理解
查看>>
leetcode703
查看>>
GDAL的安装和配置(编译proj.4)
查看>>
Swagger2使用记录
查看>>