python基礎(內置函數+文件操作+lambda)


一、內置函數

注:查看詳細猛擊這里

常用內置函數代碼說明:

  1 # abs絕對值
  2 # i = abs(-123)
  3 # print(i)  #返回123,絕對值
  4  
  5  
  6 # #all,循環參數,如果每個元素為真,那么all返回的為真,有一個為假返回的就是假的
  7 # a = all((None,123,456,False))
  8 # print(a)   #返回的為假的,證明中間有False值
  9 #
 10 # #所有的假值有
 11 #     #0,None,空值
 12 #
 13  
 14 # #any  只要之前有一個是真的,返回的就是真
 15 # b = any([11,False])
 16 # print(b)
 17  
 18  
 19 #ascii,去指定對象的類中找__repr__,獲取返回值
 20 # #ascii函數
 21 # class Foo:
 22 #     def __repr__(self):
 23 #         return "tina"
 24 # obj =Foo()
 25 # r = ascii(obj)
 26 # print(r)
 27  
 28  
 29 # 布爾值返回真或假
 30 # print(bool(1))
 31 # print(bool(0))
 32  

 36 # #bin二進制
 37 # r = bin(123)
 38 # print(r)
 39  
 40 # #oct八進制
 41 # r = oct(123)
 42 # print(r)
 43  
 44 # #int十進制
 45 # r = int(123)
 46 # print(r)
 47  
 48 # #hex十六進制
 49 # r = hex(123)
 50 # print(r)
 51  
 52 # #二進制轉十進制
 53 # i= int("0b11",base=2)
 54 # print(i)
 55  
 56 # #八進制轉十進制
 57 # i= int("11",base=8)
 58 # print(i)
 59  
 60 # #十六進制轉十進制
 61 # i = int("0xe",base=16)
 62 # print(i)
 63  
#  bin oct int hex   二進制  八進制  十進制  十六進制
# bin() 可以將 八 十 十六 進制 轉換成二進制
print(bin(10),bin(0o13),bin(0x14))
# oct() 可以將 二 十 十六 進制 轉換為八進制
print(oct(10),oct(0b101),oct(0x14))
# int() 可以將 二 八 十六進制轉換為十進制
print(int(0o13),int(0b101),int(0x14))
# hex() 可以將 二 八 十 進制轉換為十六進制
print(hex(0b101),hex(110),hex(0o12))

64 # #數字代表字母 65 # c = chr(66)chr()輸入數字,找到ascii碼對應的字母 66 # print(c) 67 68 # #字母代表數字 69 # c = ord("a") 70 # print(c) 73 #bytes, 字節 74 #字節和字符串的轉換 75 # a = bytes("tina",encoding="utf-8") 76 # print(a) 77 #bytearray 字節列表 81 #chr(),把數字轉換成字母,只適用於ascii碼 82 # a = chr(65) 83 # print(a) 84 85 #ord(),把字母轉換成數字,只適用於ascii碼 86 # a = ord("a") 87 # print(a) 88 89 #callable表示一個對象是否可執行 90 # def f1(): #看這個函數能不能執行,能則返回True 91 # return 123 92 # f1() 93 # r = callable(f1) 94 # print(r) 98 #dir,查看一個類里面存在的功能 99 # li = [] 100 # print(dir(li)) 101 # help(list) 102 103 104 #divmod(),#分頁的時候使用 105 # a = 10/3 106 # r = divmod(10,3) 107 # print(r) 108 109 110 111 #compile編譯, 把字符串轉移成python可執行的代碼,知道就行 112 113 #eval(),簡單的表達式,可以給算出來 114 # b = eval("a + 69" , {"a":99}) #a可以通過字典聲明變量去寫入 115 # print(b) 116 117 #exec,不會返回值,直接輸出結果 118 # exec("for i in range(10):print(i)") 119 120 121 # filter對於序列中的元素進行篩選,最終獲取符合條件的序列(需要循環) 122 # def f1(x): 123 # if x >22: 124 # return True 125 # else: 126 # return False 127 # 128 # ret = filter(f1,[11,22,33,44,55]) 129 # for i in ret: 130 # print(i) 131 132 # ret = filter(lambda x: x > 22, [11, 22, 33, 44, 55, 66, 77]) 133 # for i in ret: 134 # print(i) 135 136 #map(函數,可以迭代的對象,讓元素統一操作) 137 # def f1(x): 138 # return x+123 139 # 140 # # li = [11,22,33,44,55,66] 141 # # ret = map(f1,li) 142 # print(ret) 143 # for i in ret: 144 # print(i) 145 # 146 # ret = map(lambda x: x + 100 if x%2==1 else x, [11, 22, 33, 44]) 147 # print(ret) 148 # for i in ret: 149 # print(i) 150 151 #globals()獲取當前所有的全局變量 152 153 #locals()獲取當前所有的局部變量 154 # ret = "asziusdhf" 155 # def fu1(): 156 # name = 123 157 # print(locals()) 158 # print(globals()) 159 # 160 # fu1() 161 162 163 #hash 對key的優化,相當於給輸出一種哈希值 164 # li = "sdglgmdgongoaerngonaeorgnienrg" 165 # print(hash(li)) 166 167 #isinstance()判斷是不是一個類型 168 # li = [11,22] 169 # ret = isinstance(li,list) 170 # print(ret) ############小案例#######################
def obj_len(a):
    if isinstance(a,str) or isinstance(a,list) or isinstance(a,tuple):
        if len(a)>5:
            return True
        else:
            return False
    return None
t = [111,22,2,2,]
tt = obj_len(t)
print(tt)
173 #iter創建一個可以被迭代的元素
174 # obj = iter([11,22,33,44])
175 # print(obj)
176 # #next,取下一個值,一個變量里的值可以一直往下取,直到沒有就報錯
177 # ret = next(obj)
178  
179 #max()取最大的值
180 # li = [11,22,33,44]
181 # ret = max(li)
182 # print(ret)
183  
184 #min()取最小值
185 # li = [11,22,33,44]
186 # ret = min(li)
187 # print(ret)
188  
189 #求一個數字的多少次方
190 # ret = pow(2,10)
191 # print(ret)
192  
193 #reversed反轉
194 # a = [11,22,33,44]
195 # b = reversed(a)
196 # for i in b:
197 #     print(i)
198  
199 #round 四舍五入
200 # ret = round(4.8)
201 # print(ret)
202  
203 #sum求和
204 # ret = sum((11,22,33,44))
205 # print(ret)
206  
207 #zip,1 1對應
208 # li1 = [11,22,33,44,55]
209 # li2 = [99,88,77,66,89]
210 # dic = dict(zip(li1,li2))
211 # print(dic)
212  
213  
214 #sorted 排序
215 # li = ["1","2sdg;l","57","a","b","A","中國人"]
216 # lis = sorted(li)
217 # print(lis)
218 # for i in lis:
219 #     print(bytes(i,encoding="utf-8"))
######################小案例:############################
224 # #隨機生成6位驗證碼
225 # import random
226 # temp = ''
227 # for i in range(6):
228 #     num = random.randrange(0,4)
229 #     if num ==3 or num ==1:
230 #         rad1 = random.randrange(0,10)
231 #         temp+=str(rad1)
232 #     else:
233 #         rad2 = random.randrange(65,91)
234 #         c1 = chr(rad2)
235 #         temp+=c1
236 # print(temp)

二、文件處理

1、打開文件

 文件句柄 = open('文件路徑', '模式')

打開文件時,需要指定文件路徑和以何等方式打開文件,打開后,即可獲取該文件句柄,日后通過此文件句柄對該文件操作。

打開文件的模式有:

  • r ,只讀模式【默認】
  • w,只寫模式【不可讀;不存在則創建;存在則清空內容;】
  • x, 只寫模式【不可讀;不存在則創建,存在則報錯】
  • a, 追加模式【不可讀;   不存在則創建;存在則只追加內容;】

"+" 表示可以同時讀寫某個文件

  • r+, 讀寫【可讀,可寫】
  • w+,寫讀【可讀,可寫】
  • x+ ,寫讀【可讀,可寫】
  • a+, 寫讀【可讀,可寫】

 "b"表示以字節的方式操作

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

 注:以b方式打開時,讀取到的內容是字節類型,寫入時也需要提供字節類型

#普通方式打開
# ====python內部將二進制轉換成字符串,通過字符串操作
 
#二進制打開方式
#用戶自己操作把字符串轉成二進制,然后讓電腦識別
 
 
# 1. 只讀模式,r
# a = open("1.log","r")   #打開1.log,賦予只讀的權限
# ret = a.read()        #讀取文件
# a.close()            #退出文件
# print(ret)             #打印文件內容
 
#2.只寫模式,w, 如果不存在會創建文件,存在則清空內容
# a = open("3.log","w")
# a.write("sdfhsuigfhuisg")
# a.close()
 
#3.只寫模式,x, 如果不存在會創建文件,存在則報錯
# a = open("4.log","x")
# a.write("12345678")
# a.close()
 
#4.追加模式,a,不可讀,不存在則創建文件,存在則會追加內容
# a = open("4.log","a")
# a.write("asjfioshf")
# a.close()
 
# "b"表示處理二進制文件(如:FTP發送上傳ISO鏡像文件,linux可忽略,windows處理二進制文件時需標注)
 
#5.只讀模式,rb,以字節方式打開,默認打開是字節的方式
# a = open("2.log","rb")    #二進制方式讀取2.log文件
# date = a.read()            #定義變量,讀文件
# a.close()                  #關閉文件
# print(date)                #打印文件
# str_data = str(date, encoding="utf-8")    #字節轉換成utf-8
# print(str_data)            # 打印文件
 
 
#6.只寫模式,wb,
# a = open("2.log","wb")     #打開文件2.log,可寫的模式
# date = "中國人"             #定義字符串
# a.write(bytes(date , encoding="utf-8")) #轉換成字節,方便計算機識別
# a.close()                    #關閉文件
# print(date)                  #打印出來
 
 
#7.只寫模式,xb,
# a = open("6.log","xb")
# date = "哈哈哈"
# # a.write("sakfdhisf")   #字符串形式會報錯,計算機不識別,得轉換成字節
# a.write(bytes(date,encoding="utf-8"))
# a.close()
# print(date)
 
 
#8.追加模式,ab,
# a = open("5.log","ab")
# date = "呵呵呵"
# a.write(bytes(date,encoding="utf-8"))
# a.close()
# print(date)
 
 
# #"+"表示具有讀寫的功能
 
# #9.r+,讀寫(可讀,可寫)
# a = open("5.log","r+",encoding="utf-8")
# print(a.tell())    #打開文件后觀看指針位置在第幾位,默認在起始位置
#
# date = a.read()       #第一次讀取,指針讀取到最后了,(可以加讀取的索引位置,3表示只看前三位)
# print(date)
#
# a.write("嘿嘿嘿")      #寫的時候會把指針調到最后去寫
#
# a.seek(0)           #把指針放在第一位進行第二次讀取
#
# date = a.read()       #第二次讀取
# print(date)
# a.close()
 
#10.w+,寫讀,(可寫,可讀),先清空內容,在寫之后需要把指針放在第一位才能讀 # a = open("5.log","w+",encoding="utf-8") # a.write("哦哦") #清空內容寫入“哦哦” # a.seek(0) #把指針放在第一位 # date = a.read() #進行讀取 # a.close() #退出文件 # print(date) #11.x+,寫讀,(可寫,可讀),需要創建一個新文件,文件存在會報錯,在寫之后需要把指針放在第一位才能讀 # a = open("7.log","x+",encoding="utf-8") # a.write("嘻嘻嘻") #清空內容寫入“嘻嘻嘻” # a.seek(0) #把指針放在第一位 # date = a.read() #進行讀取 # a.close() #退出文件 # print(date) #12.a+,寫讀,(可寫,可讀),打開文件的同時,指針已經在最后了 # a = open("5.log","a+",encoding="utf-8") # date = a.read() #第一次讀,沒數據,因為指針在最后 # print(date) # # a.write("嗯嗯") #往最后寫入 嗯嗯 # # a.seek(0) #把指針放在第一位,讓他進行曲讀 # date = a.read() # print(date) # # a.close()

2、文件操作方法:

class TextIOWrapper(_TextIOBase):
    """
    Character and line based layer over a BufferedIOBase object, buffer.
    
    encoding gives the name of the encoding that the stream will be
    decoded or encoded with. It defaults to locale.getpreferredencoding(False).
    
    errors determines the strictness of encoding and decoding (see
    help(codecs.Codec) or the documentation for codecs.register) and
    defaults to "strict".
    
    newline controls how line endings are handled. It can be None, '',
    '\n', '\r', and '\r\n'.  It works as follows:
    
    * On input, if newline is None, universal newlines mode is
      enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
      these are translated into '\n' before being returned to the
      caller. If it is '', universal newline mode is enabled, but line
      endings are returned to the caller untranslated. If it has any of
      the other legal values, input lines are only terminated by the given
      string, and the line ending is returned to the caller untranslated.
    
    * On output, if newline is None, any '\n' characters written are
      translated to the system default line separator, os.linesep. If
      newline is '' or '\n', no translation takes place. If newline is any
      of the other legal values, any '\n' characters written are translated
      to the given string.
    
    If line_buffering is True, a call to flush is implied when a call to
    write contains a newline character.
    """
    def close(self, *args, **kwargs): # real signature unknown
        關閉文件
        pass

    def fileno(self, *args, **kwargs): # real signature unknown
        文件描述符  
        pass

    def flush(self, *args, **kwargs): # real signature unknown
        刷新文件內部緩沖區
        pass

    def isatty(self, *args, **kwargs): # real signature unknown
        判斷文件是否是同意tty設備
        pass

    def read(self, *args, **kwargs): # real signature unknown
        讀取指定字節數據
        pass

    def readable(self, *args, **kwargs): # real signature unknown
        是否可讀
        pass

    def readline(self, *args, **kwargs): # real signature unknown
        僅讀取一行數據
        pass

    def seek(self, *args, **kwargs): # real signature unknown
        指定文件中指針位置
        pass

    def seekable(self, *args, **kwargs): # real signature unknown
        指針是否可操作
        pass

    def tell(self, *args, **kwargs): # real signature unknown
        獲取指針位置
        pass

    def truncate(self, *args, **kwargs): # real signature unknown
        截斷數據,僅保留指定之前數據
        pass

    def writable(self, *args, **kwargs): # real signature unknown
        是否可寫
        pass

    def write(self, *args, **kwargs): # real signature unknown
        寫內容
        pass

    def __getstate__(self, *args, **kwargs): # real signature unknown
        pass

    def __init__(self, *args, **kwargs): # real signature unknown
        pass

    @staticmethod # known case of __new__
    def __new__(*args, **kwargs): # real signature unknown
        """ Create and return a new object.  See help(type) for accurate signature. """
        pass

    def __next__(self, *args, **kwargs): # real signature unknown
        """ Implement next(self). """
        pass

    def __repr__(self, *args, **kwargs): # real signature unknown
        """ Return repr(self). """
        pass

    buffer = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    closed = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    encoding = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    errors = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    line_buffering = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    name = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    newlines = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _CHUNK_SIZE = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

    _finalizing = property(lambda self: object(), lambda self, v: None, lambda self: None)  # default

3.x
3.0
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
(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

2.x
2.0
1 a = open("5.log","r+",encoding="utf-8")
2 # a.truncate()     #依賴於指針,截取數據,只剩下指針所在位置的前面的數據
3 # a.close()        #關閉
4 # a.flush()        #強行加入內存
5 # a.read()         #讀
6 # a.readline()     #只讀取第一行
7 # a.seek(0)        #指針
8 # a.tell()         #當前指針位置
9 # a.write()        #寫

3、文件上下文管理

為了避免打開文件后忘記關閉,可以通過管理上下文,即:

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

如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源。

在Python 2.7 及以后,with又支持同時對多個文件的上下文進行管理,即:

1
2
with  open ( 'log1' ) as obj1,  open ( 'log2' ) as obj2:
     pass

例:

1
2
3
4
5
6
7
8
#關閉文件with
with  open ( "5.log" , "r" ) as a:
     a.read()
 
#同事打開兩個文件,把a復制到b中,讀一行寫一行,直到寫完
with  open ( "5.log" , "r" ,encoding = "utf-8" ) as a, open ( "6.log" , "w" ,encoding = "utf-8" ) as b:
     for  line  in  a:
         b.write(line)

三、lambda表達式

學習條件運算時,對於簡單的 if else 語句,可以使用三元運算來表示,即:

1
2
3
4
5
6
7
8
# 普通條件語句
if  1  = =  1 :
     name  =  'wupeiqi'
else :
     name  =  'alex'
    
# 三元運算
name  =  'wupeiqi'  if  1  = =  1  else  'alex'

對於簡單的函數,也存在一種簡便的表示方式,即:lambda表達式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# ###################### 普通函數 ######################
# 定義函數(普通方式)
def  func(arg):
     return  arg  +  1
    
# 執行函數
result  =  func( 123 )
    
# ###################### lambda ######################
    
# 定義函數(lambda表達式)
my_lambda  =  lambda  arg : arg  +  1
    
# 執行函數
result  =  my_lambda( 123 )


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM