码迷,mamicode.com
首页 > 编程语言 > 详细

python学习笔记-day03 (函数和文件操作)

时间:2015-11-10 01:49:00      阅读:257      评论:0      收藏:0      [点我收藏+]

标签:python   文件操作   function   open   with   file   


函数(代码块,按功能划分(也可按其他方式划分))

内置函数
第三方函数
自定义函数


内置函数:
help()
dir()
type()
reload()
id()

vars()  # 获取脚本中的变量,当前模块的所有变量
    {‘__name__‘: ‘__main__‘,  #被执行的脚本,__name__ 的值为__main__
    ‘__builtins__‘: <module ‘__builtin__‘ (built-in)>,
    ‘__file__‘: ‘/PYthon/test/test.py‘,    #获得文件的路径(含文件名)
    ‘__doc__‘: ‘‘,      #文件的注释内容(三引号中的)
    ‘__package__‘: None
     }

all()  #接收一个序列,进行判断,如果所有值为真 ,则返回真,否则返回假

any()  #接收一个序列,进行判断,只要有一个值为真 ,则返回真,否则返回假


chr()   接收一个数字,返回其ascii对应的字符
ord()   接收一个字符,返回其ascii的值

hex()   返回16进制的数字
oct()   返回8进制的数字
bin()   返回2进制的数字

enumerate() # 枚举
    lst = [11,22,33,44,55]
    for k,v in enumerate(lst):
        print k,v
    结果:
    0 11
    1 22
    2 33
    3 44
    4 55
    
    lst = [11,22,33,44,55]
    for k,v in enumerate(lst,1):  # 可指定起始数字
        print k,v
    1 11
    2 22
    3 33
    4 44
    5 55




自定义函数

1.通过def 关键字 定义函数
2.函数名,供调用
3.函数声明时,不执行,调用时,才执行
4.函数的参数
    普通参数
    默认参数:不传参数,则使用默认参数;需要放在参数列表最后,否则报错。
    动态参数:
            1. 可以接收多个参数;内部自动构造元组;传序列时,通过加* 来避免构造元组;
            def func(*args):
                print args  ##args[0]   可打印参数第一个类,其他以此类推
            lst = [1,2,3]
            func(lst)
            func(*lst)
            输出:
            ([1, 2, 3],)
            (1, 2, 3)
            
            2. 可接收多个参数时,内部自动构造字典,传参数时,通过使用** 来避免传参数错误。
            def func(**kwargs):
                print kwargs
            dic={‘k1‘:123,‘k2‘:456}
            func(k1=123)
            func(**dic)
            输出:
            {‘k1‘: 123}
            {‘k2‘: 456, ‘k1‘: 123}

5.函数的返回值: 没有return时,返回None,如果有return ,返回return值



python中的函数使用小括号调用,函数调用前必须先定义。如果函数中没有return语句,就会自动返回None对象。
python是通过引用调用的,即:函数内对参数的改变会影响到原始对象,不过事实上只有可变对象会受此影响,
对不可变对象来说,他的行为类似按值调用。


如何定义函数
def function_name([arguments]):
    "optional documentation string"
    function_suite
    return ‘123‘  # 该语句不是必须的。
     
定义一个函数的语法由 def 关键字及紧随其后的函数名在加上该函数需要的几个参数组成。
函数参数是可选的,中括号表是可选,实际代码中要避免出现。该语句由冒号结束,同 if 语句
然后是函数体语句
例:
    def alert(arg):
        """This is doc"""
        print "This is statment of function,arg is",arg


参数:
函数的参数可以有一个默认值,如果有默认值,在函数中定义,并以赋值语句的形式提供,这样函数的参数就
有了默认值,在调用函数时,如果没有提供这个参数,该参数的值就是默认值

    def foo(debug=True):
        ‘‘‘doc‘‘‘
        if debug:
            print "True"
        else:
            print "False"
    foo()
    True
    foo(False)
    False

如上所示,debug的默认值是True,如果我们没有传递参数给函数foo(),那么debug就会自动的设置值为True,
如果传递了一个参数值,那么函数的参数就会以传递的参数值为参数的值。









邮件发送代码:
import smtplib
from email.mime.text import MIMEText
from email.utils import formataddr

def send_mail():
    msg = MIMEText(‘邮件内容‘, ‘plain‘, ‘utf-8‘)
    msg[‘From‘] = formataddr(["武沛齐",‘wptawy@126.com‘])
    msg[‘To‘] = formataddr(["走人",‘424662508@qq.com‘])
    msg[‘Subject‘] = "主题"

    server = smtplib.SMTP("smtp.126.com", 25)
    server.login("wptawy@126.com", "邮箱密码")
    server.sendmail(‘wptawy@126.com‘, [‘424662508@qq.com‘,], msg.as_string())
    server.quit()



################################################################################

文件操作
1.打开文件
    文件句柄 = open(‘文件‘,‘模式‘)
    打开文件的方式有两种 open() file(),本质上open()调用的file(), 推荐使用open();
    由于python升级的原因,file()可能会有变动,但是open()不会改变
    模式:
        r : 只读模式,读取文件
        w : 只写模式,不可读,文件不存在时则创建,文件存在则删除内容。
        a : 追加模式,可读,不存在则创建,存在则只追加内容。
        r+: 可读写文件,可读 可写 可追加
        rU  "U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r 或 r+ 模式同使用)
        r+U

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

2.操作文件
    seek()  # 指定操作文件的指针的位置
    tell()  #获取操作文件的指针的当前位置
    truncate()  #截断文件,截断当前指针位置之后的内容,即删除,指针前面的文件会保留
                如果指定位置,则从指定位置开始截断



class file(object):
    """
    file(name[, mode[, buffering]]) -> file object
    
    Open a file.  The mode can be ‘r‘, ‘w‘ or ‘a‘ for reading (default),
    writing or appending.  The file will be created if it doesn‘t exist
    when opened for writing or appending; it will be truncated when
    opened for writing.  Add a ‘b‘ to the mode for binary files.
    Add a ‘+‘ to the mode to allow simultaneous reading and writing.
    If the buffering argument is given, 0 means unbuffered, 1 means line
    buffered, and larger numbers specify the buffer size.  The preferred way
    to open a file is with the builtin open() function.
    Add a ‘U‘ to mode to open the file for input with universal newline
    support.  Any line ending in the input file will be seen as a ‘\n‘
    in Python.  Also, a file so opened gains the attribute ‘newlines‘;
    the value for this attribute is one of None (no newline read yet),
    ‘\r‘, ‘\n‘, ‘\r\n‘ or a tuple containing all the newline types seen.
    
    ‘U‘ cannot be combined with ‘w‘ or ‘+‘ mode.
    """
    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.
        """
        pass

    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__
        """ isatty() -> true or false.  True if the file is connected to a tty device.
        判断文件是否同意tty设备
        """
        return False

    def next(self): # real signature unknown; restored from __doc__
        """ x.next() -> the next value, or raise StopIteration
        获取下一行数据,如果没有下一行数据就会报错 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

    def __delattr__(self, name): # real signature unknown; restored from __doc__
        """ x.__delattr__(‘name‘) <==> del x.name """
        pass

    def __enter__(self): # real signature unknown; restored from __doc__
        """ __enter__() -> self. """
        return self

    def __exit__(self, *excinfo): # real signature unknown; restored from __doc__
        """ __exit__(*excinfo) -> None.  Closes the file. """
        pass

    def __getattribute__(self, name): # real signature unknown; restored from __doc__
        """ x.__getattribute__(‘name‘) <==> x.name """
        pass

    def __init__(self, name, mode=None, buffering=None): # real signature unknown; restored from __doc__
        pass

    def __iter__(self): # real signature unknown; restored from __doc__
        """ x.__iter__() <==> iter(x) """
        pass

    @staticmethod # known case of __new__
    def __new__(S, *more): # real signature unknown; restored from __doc__
        """ T.__new__(S, ...) -> a new object with type S, a subtype of T """
        pass

    def __repr__(self): # real signature unknown; restored from __doc__
        """ x.__repr__() <==> repr(x) """
        pass

    def __setattr__(self, name, value): # real signature unknown; restored from __doc__
        """ x.__setattr__(‘name‘, value) <==> x.name = value """
        pass

    closed = property(lambda self: True)
    """True if the file is closed

    :type: bool
    """

    encoding = property(lambda self: ‘‘)
    """file encoding

    :type: string
    """

    errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default
    """Unicode error handler"""

    mode = property(lambda self: ‘‘)
    """file mode (‘r‘, ‘U‘, ‘w‘, ‘a‘, possibly with ‘b‘ or ‘+‘ added)

    :type: string
    """

    name = property(lambda self: ‘‘)
    """file name

    :type: string
    """

    newlines = property(lambda self: ‘‘)
    """end-of-line convention used in this file

    :type: string
    """

    softspace = property(lambda self: True)
    """flag indicating that a space needs to be printed; used by print

    :type: bool
    """



########################################################################################

with语句
1.避免忘记关闭文件句柄
2.文件读取发生异常
3. 支持打开多个文件,2.7以后开始支持

使用方法:
with open(‘file‘,‘r‘)  as f:
    data=f.read()

with open(‘file1‘,‘r‘) as f1, open(‘file2‘,‘r‘) as f2:
       pass


51cto博客地址

http://timesnotes.blog.51cto.com

http://timesnotes.blog.51cto.com/1079212/1711145

本博客地址:

http://www.timesnotes.com/

http://www.timesnotes.com/?p=91


本文出自 “Will的笔记” 博客,请务必保留此出处http://timesnotes.blog.51cto.com/1079212/1711230

python学习笔记-day03 (函数和文件操作)

标签:python   文件操作   function   open   with   file   

原文地址:http://timesnotes.blog.51cto.com/1079212/1711230

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!