python之路函数

1、函数参数,引用

2、lambda表达式

  

              lambda表达式

 

 1 f1 = lambda a1,a2: a1+a2 

3、python的内置函数

  abs(),绝对值

  all(),循环参数,如果每个元素都为真,那么all返回值为真

    0是假的,None 是假,“”,[],(),{},空值都是假的

  any() 只要有一个是真则为真

  ascii(对象),去对象的类中找_repr_,获取返回值

  bin(),二进制

  oct(),八进制

  int(),十进制

  hex(),十六进制

   bool(), 判断真假,把一个对象转换成bool值,None,“”,【】,{}

  bytes   字节

  bytearray   字节列表

  字节转字符串

  bytes(“xxx”, encoding=‘utf-8’)

  chr(),把数字转换成asc码,对应的字符

  ord(),把字符转化成数字

    实例:生成一个随机验证码

 1 #!/usr/bin/env python
 2 # -*- coding: utf-8 -*-
 3 
 4 import random
 5 
 6 temp = ""
 7 for i in range(6):
 8     # 生成0-4的随机数
 9     num = random.randrange(0, 4)
10     # 如果随机数是1或3,那么就在验证码中生成一个0-9的随机数字
11     # 否则,验证码中生成一个随机字母
12     if num == 3 or num == 1:
13         rad2 = random.randrange(0, 10)
14         temp = temp + str(rad2)
15     else:
16         rad1 = random.randrange(65, 91)
17         c1 = chr(rad1)
18         temp = temp + rad1
19 print(temp)
验证码代码

   callable(),能不能执行

  compile(),编译

  complex(),

  dir(),看看函数提供的功能

  divmod(),计算需要多少页

    

   eval(),可以执行一个字符串形式的字符串,有返回值

  exec(),执行python代码

     

    

  一、 map(函数,可迭代的对象),让所有的数统一做个操作

1 li = [11, 22, 33]
2 
3 new_list = map(lambda a: a + 100, li)
View Code
1 li = [11, 22, 33]
2 sl = [1, 2, 3]
3 new_list = map(lambda a, b: a + b, li, sl)
View Code

  二、filter(函数,可迭代的对象),过滤,循环可迭代的对象,获取每一个参数,

 

1 li = [11, 22, 33]
2 
3 new_list = filter(lambda arg: arg > 22, li)
4 
5 #filter第一个参数为空,将获取原来序列
View Code    

1 li = [11, 22, 33]
2 
3 result = reduce(lambda arg1, arg2: arg1 + arg2, li)
4 
5 # reduce的第一个参数,函数必须要有两个参数
6 # reduce的第二个参数,要循环的序列
7 # reduce的第三个参数,初始值
View Code 

  format()字符串格式化

  globals()获取所有的全局变量

  locals()获取所有的局部变量

  hash()算哈希值

  isinstance(),判断某个对象是否有某个类创建的

  issubclass(),是不是子类

  open()打开文件

  pow(),求指数

  repr()====ascii(),

  round()四舍五入

  silce(),去对象的索引

  vars()一个对象有的变量

 

 字符串不能排序

1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 
4 li = [1, 2, 22, 333, 444]
5 new_li = sorted(li)
6 print(new_li)
View Code

                  文件操作

 

一、打开文件

  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

以字节的方式打开

1、只读  rb

 

二、操作文件

  1 class file(object):
  2   
  3     def close(self): # real signature unknown; restored from __doc__
  4         关闭文件
  5         """
  6         close() -> None or (perhaps) an integer.  Close the file.
  7          
  8         Sets data attribute .closed to True.  A closed file cannot be used for
  9         further I/O operations.  close() may be called more than once without
 10         error.  Some kinds of file objects (for example, opened by popen())
 11         may return an exit status upon closing.
 12         """
 13  
 14     def fileno(self): # real signature unknown; restored from __doc__
 15         文件描述符  
 16          """
 17         fileno() -> integer "file descriptor".
 18          
 19         This is needed for lower-level file interfaces, such os.read().
 20         """
 21         return 0    
 22  
 23     def flush(self): # real signature unknown; restored from __doc__
 24         刷新文件内部缓冲区
 25         """ flush() -> None.  Flush the internal I/O buffer. """
 26         pass
 27  
 28  
 29     def isatty(self): # real signature unknown; restored from __doc__
 30         判断文件是否是同意tty设备
 31         """ isatty() -> true or false.  True if the file is connected to a tty device. """
 32         return False
 33  
 34  
 35     def next(self): # real signature unknown; restored from __doc__
 36         获取下一行数据,不存在,则报错
 37         """ x.next() -> the next value, or raise StopIteration """
 38         pass
 39  
 40     def read(self, size=None): # real signature unknown; restored from __doc__
 41         读取指定字节数据
 42         """
 43         read([size]) -> read at most size bytes, returned as a string.
 44          
 45         If the size argument is negative or omitted, read until EOF is reached.
 46         Notice that when in non-blocking mode, less data than what was requested
 47         may be returned, even if no size parameter was given.
 48         """
 49         pass
 50  
 51     def readinto(self): # real signature unknown; restored from __doc__
 52         读取到缓冲区,不要用,将被遗弃
 53         """ readinto() -> Undocumented.  Don't use this; it may go away. """
 54         pass
 55  
 56     def readline(self, size=None): # real signature unknown; restored from __doc__
 57         仅读取一行数据
 58         """
 59         readline([size]) -> next line from the file, as a string.
 60          
 61         Retain newline.  A non-negative size argument limits the maximum
 62         number of bytes to return (an incomplete line may be returned then).
 63         Return an empty string at EOF.
 64         """
 65         pass
 66  
 67     def readlines(self, size=None): # real signature unknown; restored from __doc__
 68         读取所有数据,并根据换行保存值列表
 69         """
 70         readlines([size]) -> list of strings, each a line from the file.
 71          
 72         Call readline() repeatedly and return a list of the lines so read.
 73         The optional size argument, if given, is an approximate bound on the
 74         total number of bytes in the lines returned.
 75         """
 76         return []
 77  
 78     def seek(self, offset, whence=None): # real signature unknown; restored from __doc__
 79         指定文件中指针位置
 80         """
 81         seek(offset[, whence]) -> None.  Move to new file position.
 82          
 83         Argument offset is a byte count.  Optional argument whence defaults to
 84         0 (offset from start of file, offset should be >= 0); other values are 1
 85         (move relative to current position, positive or negative), and 2 (move
 86         relative to end of file, usually negative, although many platforms allow
 87         seeking beyond the end of a file).  If the file is opened in text mode,
 88         only offsets returned by tell() are legal.  Use of other offsets causes
 89         undefined behavior.
 90         Note that not all file objects are seekable.
 91         """
 92         pass
 93  
 94     def tell(self): # real signature unknown; restored from __doc__
 95         获取当前指针位置
 96         """ tell() -> current file position, an integer (may be a long integer). """
 97         pass
 98  
 99     def truncate(self, size=None): # real signature unknown; restored from __doc__
100         截断数据,仅保留指定之前数据
101         """
102         truncate([size]) -> None.  Truncate the file to at most size bytes.
103          
104         Size defaults to the current file position, as returned by tell().
105         """
106         pass
107  
108     def write(self, p_str): # real signature unknown; restored from __doc__
109         写内容
110         """
111         write(str) -> None.  Write string str to file.
112          
113         Note that due to buffering, flush() or close() may be needed before
114         the file on disk reflects the data written.
115         """
116         pass
117  
118     def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__
119         将一个字符串列表写入文件
120         """
121         writelines(sequence_of_strings) -> None.  Write the strings to the file.
122          
123         Note that newlines are not added.  The sequence can be any iterable object
124         producing strings. This is equivalent to calling write() for each string.
125         """
126         pass
127  
128     def xreadlines(self): # real signature unknown; restored from __doc__
129         可用于逐行读取文件,非全部
130         """
131         xreadlines() -> returns self.
132          
133         For backward compatibility. File objects now include the performance
134         optimizations previously implemented in the xreadlines module.
135         """
136         pass
View Code

 f.tell()# 获取指针的位置

 f.seek(num)#调整指针的位置

truncate()截取数据,仅保留指定之前的数据

要掌握的内容

三、关闭文件                                                        

1 with open('log','r') as f:
2      
3     ...
View Code

                                                

   自动关闭

with支持同时打开两个文件

 

原文地址:https://www.cnblogs.com/minmin123/p/8639708.html