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

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

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

内置函数:
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(["武沛齐",‘[email protected]‘])
    msg[‘To‘] = formataddr(["走人",‘[email protected]‘])
    msg[‘Subject‘] = "主题"

server = smtplib.SMTP("smtp.126.com", 25)
    server.login("[email protected]", "邮箱密码")
    server.sendmail(‘[email protected]‘, [‘[email protected]‘,], 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

时间: 2024-07-30 13:50:40

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

python学习笔记——(三)文件操作

·集合操作及其相应的操作符表示集合中没有插入,只有添加,因为毕竟无序 #!/usr/bin/env python # -*- coding:utf-8 -*- # Author:Vergil Zhang list_1 = [1, 4, 5, 7, 3, 6, 7, 9] list_1 = set(list_1) print(list_1, type(list_1)) list_2 = set([2, 6, 0, 66, 22, 8]) print(list_1,list_2) #交集 print

Python学习笔记3:简单文件操作

# -*- coding: cp936 -*- # 1 打开文件 # open(fileName, mode) # 參数:fileName文件名称 # mode打开方式 # w     以写方式打开. # a     以追加模式打开 (从 EOF 開始, 必要时创建新文件) # r+     以读写模式打开 # w+     以读写模式打开 # a+     以读写模式打开 # rb     以二进制读模式打开 # wb     以二进制写模式打开 # ab     以二进制追加模式打开 # r

Python学习系列(五)(文件操作及其字典)

Python学习系列(五)(文件操作及其字典) Python学习系列(四)(列表及其函数) 一.文件操作 1,读文件 在以'r'读模式打开文件以后可以调用read函数一次性将文件内容全部读出,也可以指定每次read读多少字节,例如: 1 #coding:utf-8 2 fn='test1.py' 3 fp=open(fn,'r') #以读的方式打开文件,文件必须首先存在和,.文件在同一目录下py 4 print 'reading pos:',fp.tell() 5 r=fp.read(20) #

python学习笔记之函数总结--高阶函数以及装饰器

python学习笔记之函数总结--高阶函数以及装饰器 Python特点: 1.不是纯函数式编程(允许变量存在): 2.支持高阶函数(可以传入函数作为变量): 3.支持闭包(可以返回函数): 4.有限度的支持匿名函数: 高阶函数: 1.变量可以指向函数: 2.函数的参数可以接收变量: 3.一个函数可以接收另一个函数作为参数: 下面我将示例一些函数的写法以及使用,并说明python中函数的特性: 1.基本的高阶函数示例: #!/usr/bin/env python def func():      

老男孩学习 python 5 内置函数和文件操作

lambda 表达式: 内置函数: ABS:绝对值: ALL:循环参数,如果每个元素都为真,那么all的返回的值为真 ANY 只有一个真,则为真 ASCII ,利用对象中_repr_,获得返回值: INT: 将别的进制的数据转换十进制的数据: bin:将字符串转换成字节 bool  判断真假,把一个对象转换成布尔值 CHR:将10进制的数据转换成ASCII中的字母 ord:将ascii中的字符转换成十进制的字符 radmon 模块 random.randrange(1.8) 从1到8中生成随机数

python学习列表字符串字典集合文件操作字符串编码与转换

一.列表 1 names = "ZhangYang GuYun XiangPeng XuLiangchen" 2 names = ["ZhangYang", "GuYun", "XiangPeng", "ChengRongHua","XuLiangchen"] 3 names.append("LeiHaiDong") #在列表最后追加一个元素 4 names.inse

python基础总结(函数,文件操作)

一.内建函数 1.数学运算类 abs(x)#求绝对值 divmod(a, b)#分别取商和余数 float([x])#将一个字符串或数转换为浮点数.如果无参数将返回0.0 int([x[, base]])#将一个字符转换为int类型,base表示进制 long([x[, base]])#将一个字符转换为long类型 range([start], stop[, step]) #产生一个序列,默认从0开始 oct(x)#将一个数字转化为8进制 hex(x)#将整数x转换为16进制字符串 chr(i)

Python学习笔记003_函数

>>> # 函数>>> def myFirstFunction(params1,params2...): print("这是我的第一个函数!") print("Python你好吗?") >>> #调用函数>>> >>> myFirstFunction()这是我的第一个函数!Python你好吗? >>>  # 函数的返回值  return #函数文档, 就是函数

python学习点滴记录-Day02补充-文件操作

字符编码: 把人类的字符翻译成计算机能认识的数字 字符编码表 存放着人类字符和计算机数字的对应关系表 ascii.gbk.utf-8.unicode unicode>encode(utf8)>bytes bytes>decode(utf8)>unicode 文件处理补充: 字符以什么格式编码的,就要以什么格式解码 文件的打开模式 文件句柄 = open('文件路径', '模式') 打开文件时,需要指定文件路径和以何等方式打开文件,打开后,即可获取该文件句柄,日后通过此文件句柄对该文