Python 語法速覽與實戰清單(python是什么意思)

      網友投稿 904 2022-05-30

      注:鑒于博客內容有限與格式錯亂,原始 MarkDown 文檔存放在了附件中。

      Python 語法速覽與實戰清單

      本文是對于?現代 Python 開發:語法基礎與工程實踐的總結,更多 Python 相關資料參考?Python 學習與實踐資料索引;本文參考了?Python Crash Course - Cheat Sheets,pysheeet?等。本文僅包含筆者在日常工作中經常使用的,并且認為較為關鍵的知識點與語法,如果想要進一步學習 Python 相關內容或者對于機器學習與數據挖掘方向感興趣,可以參考程序猿的數據科學與機器學習實戰手冊。

      基礎語法

      Python 是一門高階、動態類型的多范式編程語言;定義 Python 文件的時候我們往往會先聲明文件編碼方式 :

      #?指定腳本調用方式#!/usr/bin/env?python#?配置?utf-8?編碼#?-*-?coding:?utf-8?-*-#?配置其他編碼#?-*-?coding:??-*-#?Vim?中還可以使用如下方式#?vim:fileencoding=

      人生苦短,請用 Python,大量功能強大的語法糖的同時讓很多時候 Python 代碼看上去有點像偽代碼。譬如我們用 Python 實現的簡易的快排相較于 Java 會顯得很短小精悍 :

      def?quicksort(arr):????if?len(arr)?<=?1:????????return?arr ????pivot?=?arr[len(arr)?/?2] ????left?=?[x?for?x?in?arr?if?x??pivot]????return?quicksort(left)?+?middle?+?quicksort(right)print?quicksort([3,6,8,10,1,2,1])#?Prints?"[1,?1,?2,?3,?6,?8,?10]"

      控制臺交互

      可以根據?__name__?關鍵字來判斷是否是直接使用 python 命令執行某個腳本,還是外部引用;Google 開源的 fire 也是不錯的快速將某個類封裝為命令行工具的框架:

      import?fireclass?Calculator(object):??"""A?simple?calculator?class.""" ??def?double(self,?number):????return?2?*?numberif?__name__?==?'__main__': ??fire.Fire(Calculator)#?python?calculator.py?double?10??#?20#?python?calculator.py?double?--number=15??#?30

      Python 2 中 print 是表達式,而 Python 3 中 print 是函數;如果希望在 Python 2 中將 print 以函數方式使用,則需要自定義引入 :

      from?__future__?import?print_function

      我們也可以使用 pprint 來美化控制臺輸出內容:

      import?pprint stuff?=?['spam',?'eggs',?'lumberjack',?'knights',?'ni'] pprint.pprint(stuff)#?自定義參數pp?=?pprint.PrettyPrinter(depth=6) tup?=?('spam',?('eggs',?('lumberjack',?('knights',?('ni',?('dead',('parrot',?('fresh?fruit',)))))))) pp.pprint(tup)

      模塊

      Python 中的模塊(Module )即是 Python 源碼文件,其可以導出類、函數與全局變量;當我們從某個模塊導入變量時,函數名往往就是命名空間(Namespace )。而 Python 中的包(Package )則是模塊的文件夾,往往由?__init__.py?指明某個文件夾為包 :

      #?文件目錄someDir/ main.py siblingModule.py#?siblingModule.pydef?siblingModuleFun(): print('Hello?from?siblingModuleFun')def?siblingModuleFunTwo(): print('Hello?from?siblingModuleFunTwo')import?siblingModuleimport?siblingModule?as?sibMod sibMod.siblingModuleFun()from?siblingModule?import?siblingModuleFun siblingModuleFun()try:????#?Import?'someModuleA'?that?is?only?available?in?Windows ????import?someModuleAexcept?ImportError:????try: ????#?Import?'someModuleB'?that?is?only?available?in?Linux ????????import?someModuleB????except?ImportError:

      Package 可以為某個目錄下所有的文件設置統一入口 :

      someDir/ main.py subModules/ __init__.py subA.py subSubModules/ __init__.py subSubA.py#?subA.pydef?subAFun(): print('Hello?from?subAFun')def?subAFunTwo(): print('Hello?from?subAFunTwo')#?subSubA.pydef?subSubAFun(): print('Hello?from?subSubAFun')def?subSubAFunTwo(): print('Hello?from?subSubAFunTwo')#?__init__.py?from?subDir#?Adds?'subAFun()'?and?'subAFunTwo()'?to?the?'subDir'?namespacefrom?.subA?import?*#?The?following?two?import?statement?do?the?same?thing,?they?add?'subSubAFun()'?and?'subSubAFunTwo()'?to?the?'subDir'?namespace.?The?first?one?assumes?'__init__.py'?is?empty?in?'subSubDir',?and?the?second?one,?assumes?'__init__.py'?in?'subSubDir'?contains?'from?.subSubA?import?*'.#?Assumes?'__init__.py'?is?empty?in?'subSubDir'#?Adds?'subSubAFun()'?and?'subSubAFunTwo()'?to?the?'subDir'?namespacefrom?.subSubDir.subSubA?import?*#?Assumes?'__init__.py'?in?'subSubDir'?has?'from?.subSubA?import?*'#?Adds?'subSubAFun()'?and?'subSubAFunTwo()'?to?the?'subDir'?namespacefrom?.subSubDir?import?*#?__init__.py?from?subSubDir#?Adds?'subSubAFun()'?and?'subSubAFunTwo()'?to?the?'subSubDir'?namespacefrom?.subSubA?import?*#?main.pyimport?subDir subDir.subAFun()?#?Hello?from?subAFunsubDir.subAFunTwo()?#?Hello?from?subAFunTwosubDir.subSubAFun()?#?Hello?from?subSubAFunsubDir.subSubAFunTwo()?#?Hello?from?subSubAFunTwo

      表達式與控制流

      條件選擇

      Python 中使用 if、elif 、 else 來進行基礎的條件選擇操作:

      if?x?

      Python 同樣支持 ternary conditional operator:

      a?if?condition?else?b

      也可以使用 Tuple 來實現類似的效果:

      #?test?需要返回?True?或者?False(falseValue,?trueValue)[test]#?更安全的做法是進行強制判斷(falseValue,?trueValue)[test?==?True]#?或者使用?bool?類型轉換函數(falseValue,?trueValue)[bool()]

      循環遍歷

      for-in 可以用來遍歷數組與字典:

      words?=?['cat',?'window',?'defenestrate']for?w?in?words:????print(w,?len(w))#?使用數組訪問操作符,能夠迅速地生成數組的副本for?w?in?words[:]:????if?len(w)?>?6: ????????words.insert(0,?w)#?words?->?['defenestrate',?'cat',?'window',?'defenestrate']

      如果我們希望使用數字序列進行遍歷,可以使用 Python 內置的?range?函數:

      a?=?['Mary',?'had',?'a',?'little',?'lamb']for?i?in?range(len(a)):????print(i,?a[i])

      基本數據類型

      可以使用內建函數進行強制類型轉換(Casting ) :

      int(str)float(str)str(int)str(float)

      isinstance 方法用于判斷某個對象是否源自某個類 :

      ex?=?10#?判斷是否為?int?類型isinstance(ex,int)#?isinstance?也支持同時判斷多個類型#?如下代碼判斷是否為數組def?is_array(var):????return?isinstance(var,?(list,?tuple))

      Number: 數值類型

      x?=?3print?type(x)?#?Prints?""print?x???????#?Prints?"3"print?x?+?1???#?Addition;?prints?"4"print?x?-?1???#?Subtraction;?prints?"2"print?x?*?2???#?Multiplication;?prints?"6"print?x?**?2??#?Exponentiation;?prints?"9"x?+=?1print?x??#?Prints?"4"x?*=?2print?x??#?Prints?"8"y?=?2.5print?type(y)?#?Prints?""print?y,?y?+?1,?y?*?2,?y?**?2?#?Prints?"2.5?3.5?5.0?6.25"

      Python 語法速覽與實戰清單(python是什么意思)

      布爾類型

      Python 提供了常見的邏輯操作符,不過需要注意的是 Python 中并沒有使用 &&、|| 等,而是直接使用了英文單詞。

      t?=?Truef?=?Falseprint?type(t)?#?Prints?""print?t?and?f?#?Logical?AND;?prints?"False"print?t?or?f??#?Logical?OR;?prints?"True"print?not?t???#?Logical?NOT;?prints?"False"print?t?!=?f??#?Logical?XOR;?prints?"True"

      String: 字符串

      Python 2 中支持 Ascii 碼的 str() 類型,獨立的 unicode() 類型,沒有 byte 類型;而 Python 3 中默認的字符串為 utf-8 類型,并且包含了 byte 與 bytearray 兩個字節類型:

      type("Guido")?#?string?type?is?str?in?python2#?#?使用?__future__?中提供的模塊來降級使用?Unicodefrom?__future__?import?unicode_literalstype("Guido")?#?string?type?become?unicode#?

      Python 字符串支持分片、模板字符串等常見操作 :

      var1?=?'Hello?World!'var2?=?"Python?Programming"print?"var1[0]:?",?var1[0]print?"var2[1:5]:?",?var2[1:5]#?var1[0]:??H#?var2[1:5]:??ythoprint?"My?name?is?%s?and?weight?is?%d?kg!"?%?('Zara',?21)#?My?name?is?Zara?and?weight?is?21?kg!

      str[0:4]len(str) string.replace("-",?"?")",".join(list)"hi?{0}".format('j')str.find(",")str.index(",")???#?same,?but?raises?IndexErrorstr.count(",")str.split(",")str.lower()str.upper()str.title()str.lstrip()str.rstrip()str.strip()str.islower()

      #?移除所有的特殊字符re.sub('[^A-Za-z0-9]+',?'',?mystring)

      如果需要判斷是否包含某個子字符串,或者搜索某個字符串的下標 :

      #?in?操作符可以判斷字符串if?"blah"?not?in?somestring:????continue#?find?可以搜索下標s?=?"This?be?a?string"if?s.find("is")?==?-1:????print?"No?'is'?here!"else:????print?"Found?'is'?in?the?string."

      Regex: 正則表達式

      import?re#?判斷是否匹配re.match(r'^[aeiou]',?str)#?以第二個參數指定的字符替換原字符串中內容re.sub(r'^[aeiou]',?'?',?str) re.sub(r'(xyz)',?r'\1',?str)#?編譯生成獨立的正則表達式對象expr?=?re.compile(r'^...$') expr.match(...) expr.sub(...)

      下面列舉了常見的表達式使用場景 :

      #?檢測是否為?HTML?標簽re.search('<[^/>][^>]*>',?'')#?常見的用戶名密碼re.match('^[a-zA-Z0-9-_]{3,16}$',?'Foo')?is?not?Nonere.match('^\w|[-_]{3,16}$',?'Foo')?is?not?None#?Emailre.match('^([a-z0-9_\.-]+)@([\da-z\.-]+)\.([a-z\.]{2,6})$',?'hello.world@example.com')#?Urlexp?=?re.compile(r'''^(https?:\/\/)??#?match?http?or?https????????????????([\da-z\.-]+)????????????#?match?domain????????????????\.([a-z\.]{2,6})?????????#?match?domain????????????????([\/\w?\.-]*)\/?$????????#?match?api?or?file????????????????''',?re.X) exp.match('www.google.com')#?IP?地址exp?=?re.compile(r'''^(?:(?:25[0-5]?????????????????????|2[0-4][0-9]?????????????????????|[1]?[0-9][0-9]?)\.){3}?????????????????????(?:25[0-5]?????????????????????|2[0-4][0-9]?????????????????????|[1]?[0-9][0-9]?)$''',?re.X) exp.match('192.168.1.1')

      集合類型

      List: 列表

      Operation: 創建增刪

      list 是基礎的序列類型:

      l?=?[] l?=?list()#?使用字符串的?split?方法,可以將字符串轉化為列表str.split(".")#?如果需要將數組拼裝為字符串,則可以使用?joinlist1?=?['1',?'2',?'3'] str1?=?''.join(list1)#?如果是數值數組,則需要先進行轉換list1?=?[1,?2,?3] str1?=?''.join(str(e)?for?e?in?list1)

      可以使用 append 與 extend 向數組中插入元素或者進行數組連接

      x?=?[1,?2,?3] x.append([4,?5])?#?[1,?2,?3,?[4,?5]]x.extend([4,?5])?#?[1,?2,?3,?4,?5],注意?extend?返回值為?None

      可以使用 pop、slices 、 del、remove 等移除列表中元素:

      myList?=?[10,20,30,40,50]#?彈出第二個元素myList.pop(1)?#?20#?myList:?myList.pop(1)#?如果不加任何參數,則默認彈出最后一個元素myList.pop()#?使用?slices?來刪除某個元素a?=?[??1,?2,?3,?4,?5,?6?] index?=?3?#?Only?Positive?indexa?=?a[:index]?+?a[index+1?:]#?根據下標刪除元素myList?=?[10,20,30,40,50] rmovIndxNo?=?3del?myList[rmovIndxNo]?#?myList:?[10,?20,?30,?50]#?使用?remove?方法,直接根據元素刪除letters?=?["a",?"b",?"c",?"d",?"e"] numbers.remove(numbers[1])print(*letters)?#?used?a?*?to?make?it?unpack?you?don't?have?to

      Iteration: 索引遍歷

      你可以使用基本的 for 循環來遍歷數組中的元素,就像下面介個樣紙 :

      animals?=?['cat',?'dog',?'monk???ey']for?animal?in?animals:????print?animal#?Prints?"cat",?"dog",?"monk???ey",?each?on?its?own?line.

      如果你在循環的同時也希望能夠獲取到當前元素下標,可以使用 enumerate 函數 :

      animals?=?['cat',?'dog',?'monk???ey']for?idx,?animal?in?enumerate(animals):????print?'#%d:?%s'?%?(idx?+?1,?animal)#?Prints?"#1:?cat",?"#2:?dog",?"#3:?monk???ey",?each?on?its?own?line

      Python 也支持切片(Slices ) :

      nums?=?range(5)????#?range?is?a?built-in?function?that?creates?a?list?of?integersprint?nums?????????#?Prints?"[0,?1,?2,?3,?4]"print?nums[2:4]????#?Get?a?slice?from?index?2?to?4?(exclusive);?prints?"[2,?3]"print?nums[2:]?????#?Get?a?slice?from?index?2?to?the?end;?prints?"[2,?3,?4]"print?nums[:2]?????#?Get?a?slice?from?the?start?to?index?2?(exclusive);?prints?"[0,?1]"print?nums[:]??????#?Get?a?slice?of?the?whole?list;?prints?["0,?1,?2,?3,?4]"print?nums[:-1]????#?Slice?indices?can?be?negative;?prints?["0,?1,?2,?3]"nums[2:4]?=?[8,?9]?#?Assign?a?new?sublist?to?a?sliceprint?nums?????????#?Prints?"[0,?1,?8,?9,?4]"

      Comprehensions: 變換

      Python 中同樣可以使用 map、reduce 、 filter,map 用于變換數組 :

      #?使用?map?對數組中的每個元素計算平方items?=?[1,?2,?3,?4,?5] squared?=?list(map(lambda?x:?x**2,?items))#?map?支持函數以數組方式連接使用def?multiply(x):????return?(x*x)def?add(x):????return?(x+x) funcs?=?[multiply,?add]for?i?in?range(5): ????value?=?list(map(lambda?x:?x(i),?funcs))????print(value)

      reduce 用于進行歸納計算 :

      #?reduce?將數組中的值進行歸納from?functools?import?reduceproduct?=?reduce((lambda?x,?y:?x?*?y),?[1,?2,?3,?4])#?Output:?24

      filter 則可以對數組進行過濾 :

      number_list?=?range(-5,?5) less_than_zero?=?list(filter(lambda?x:?x?

      字典類型

      創建增刪

      d?=?{'cat':?'cute',?'dog':?'furry'}??#?創建新的字典print?d['cat']???????#?字典不支持點(Dot)運算符取值

      如果需要合并兩個或者多個字典類型:

      #?python?3.5z?=?{**x,?**y}#?python?2.7def?merge_dicts(*dict_args):????"""????Given?any?number?of?dicts,?shallow?copy?and?merge?into?a?new?dict,????precedence?goes?to?key?value?pairs?in?latter?dicts.????""" ????result?=?{}????for?dictionary?in?dict_args: ????????result.update(dictionary)????return?result

      索引遍歷

      可以根據鍵來直接進行元素訪問 :

      #?Python?中對于訪問不存在的鍵會拋出?KeyError?異常,需要先行判斷或者使用?getprint?'cat'?in?d?????#?Check?if?a?dictionary?has?a?given?key;?prints?"True"#?如果直接使用?[]?來取值,需要先確定鍵的存在,否則會拋出異常print?d['monk???ey']??#?KeyError:?'monk???ey'?not?a?key?of?d#?使用?get?函數則可以設置默認值print?d.get('monk???ey',?'N/A')??#?Get?an?element?with?a?default;?prints?"N/A"print?d.get('fish',?'N/A')????#?Get?an?element?with?a?default;?prints?"wet"d.keys()?#?使用?keys?方法可以獲取所有的鍵

      可以使用 for-in 來遍歷數組 :

      #?遍歷鍵for?key?in?d:#?比前一種方式慢for?k?in?dict.keys():?...#?直接遍歷值for?value?in?dict.itervalues():?...#?Python?2.x?中遍歷鍵值for?key,?value?in?d.iteritems():#?Python?3.x?中遍歷鍵值for?key,?value?in?d.items():

      其他序列類型

      集合

      #?Same?as?{"a",?"b","c"}normal_set?=?set(["a",?"b","c"])#?Adding?an?element?to?normal?set?is?finenormal_set.add("d")print("Normal?Set")print(normal_set)#?A?frozen?setfrozen_set?=?frozenset(["e",?"f",?"g"])print("Frozen?Set")print(frozen_set)#?Uncommenting?below?line?would?cause?error?as#?we?are?trying?to?add?element?to?a?frozen?set#?frozen_set.add("h")

      Enum

      class?Enum(set):????def?__getattr__(self,?name):????????if?name?in?self:????????????return?name????????raise?AttributeError

      函數

      函數定義

      Python 中的函數使用 def 關鍵字進行定義,譬如 :

      def?sign(x):????if?x?>?0:????????return?'positive' ????elif?x?

      Python 支持運行時創建動態函數,也即是所謂的 lambda 函數:

      def?f(x):?return?x**2#?等價于g?=?lambda?x:?x**2

      參數

      Option Arguments: 不定參數

      def?example(a,?b=None,?*args,?**kwargs):??print?a,?b??print?args??print?kwargs example(1,?"var",?2,?3,?word="hello")#?1?var#?(2,?3)#?{'word':?'hello'}a_tuple?=?(1,?2,?3,?4,?5) a_dict?=?{"1":1,?"2":2,?"3":3} example(1,?"var",?*a_tuple,?**a_dict)#?1?var#?(1,?2,?3,?4,?5)#?{'1':?1,?'2':?2,?'3':?3}

      對于不定參數的調用,同樣可以使用?**?運算符:

      func(**{'type':'Event'})#?等價于func(type='Event')

      生成器

      def?simple_generator_function():????yield?1 ????yield?2 ????yield?3for?value?in?simple_generator_function():????print(value)#?輸出結果#?1#?2#?3our_generator?=?simple_generator_function()next(our_generator)#?1next(our_generator)#?2next(our_generator)#3#?生成器典型的使用場景譬如無限數組的迭代def?get_primes(number):????while?True:????????if?is_prime(number):????????????yield?number ????????number?+=?1

      裝飾器

      裝飾器是非常有用的設計模式 :

      #?簡單裝飾器from?functools?import?wrapsdef?decorator(func):????@wraps(func)????def?wrapper(*args,?**kwargs):????????print('wrap?function')????????return?func(*args,?**kwargs)????return?wrapper@decoratordef?example(*a,?**kw):????passexample.__name__??#?attr?of?function?preserve#?'example'#?Decorator#?帶輸入值的裝飾器from?functools?import?wrapsdef?decorator_with_argument(val):??def?decorator(func):????@wraps(func)????def?wrapper(*args,?**kwargs):??????print?"Val?is?{0}".format(val)??????return?func(*args,?**kwargs)????return?wrapper??return?decorator@decorator_with_argument(10)def?example():??print?"This?is?example?function."example()#?Val?is?10#?This?is?example?function.#?等價于def?example():??print?"This?is?example?function."example?=?decorator_with_argument(10)(example) example()#?Val?is?10#?This?is?example?function.

      類與對象

      類定義

      Python 中對于類的定義也很直接 :

      class?Greeter(object):????#?Constructor ????def?__init__(self,?name):????????self.name?=?name??#?Create?an?instance?variable ????#?Instance?method ????def?greet(self,?loud=False):????????if?loud:????????????print?'HELLO,?%s!'?%?self.name.upper()????????else:????????????print?'Hello,?%s'?%?self.name g?=?Greeter('Fred')??#?Construct?an?instance?of?the?Greeter?classg.greet()????????????#?Call?an?instance?method;?prints?"Hello,?Fred"g.greet(loud=True)???#?Call?an?instance?method;?prints?"HELLO,?FRED!"

      Managed Attributes: 受控屬性

      #?property、setter、deleter?可以用于復寫點方法class?Example(object):????def?__init__(self,?value):???????self._val?=?value????@property ????def?val(self):????????return?self._val????@val.setter ????def?val(self,?value):????????if?not?isintance(value,?int):????????????raise?TypeError("Expected?int")????????self._val?=?value????@val.deleter ????def?val(self):????????del?self._val????@property ????def?square3(self):????????return?2**3ex?=?Example(123) ex.val?=?"str"#?Traceback?(most?recent?call?last):#???File?"",?line?1,?in#???File?"test.py",?line?12,?in?val#?????raise?TypeError("Expected?int")#?TypeError:?Expected?int

      類方法與靜態方法

      class?example(object):??@classmethod ??def?clsmethod(cls):????print?"I?am?classmethod" ??@staticmethod ??def?stmethod():????print?"I?am?staticmethod" ??def?instmethod(self):????print?"I?am?instancemethod"ex?=?example() ex.clsmethod()#?I?am?classmethodex.stmethod()#?I?am?staticmethodex.instmethod()#?I?am?instancemethodexample.clsmethod()#?I?am?classmethodexample.stmethod()#?I?am?staticmethodexample.instmethod()#?Traceback?(most?recent?call?last):#???File?"",?line?1,?in#?TypeError:?unbound?method?instmethod()?...

      對象

      實例化

      屬性操作

      Python 中對象的屬性不同于字典鍵,可以使用點運算符取值,直接使用 in 判斷會存在問題 :

      class?A(object):????@property ????def?prop(self):????????return?3a?=?A()print?"'prop'?in?a.__dict__?=",?'prop'?in?a.__dict__print?"hasattr(a,?'prop')?=",?hasattr(a,?'prop')print?"a.prop?=",?a.prop#?'prop'?in?a.__dict__?=?False#?hasattr(a,?'prop')?=?True#?a.prop?=?3

      建議使用 hasattr、getattr 、 setattr 這種方式對于對象屬性進行操作 :

      class?Example(object):??def?__init__(self):????self.name?=?"ex" ??def?printex(self):????print?"This?is?an?example"#?Check?object?has?attributes#?hasattr(obj,?'attr')ex?=?Example()hasattr(ex,"name")#?Truehasattr(ex,"printex")#?Truehasattr(ex,"print")#?False#?Get?object?attribute#?getattr(obj,?'attr')getattr(ex,'name')#?'ex'#?Set?object?attribute#?setattr(obj,?'attr',?value)setattr(ex,'name','example') ex.name#?'example'

      異常與測試

      異常處理

      try

      import?systry: ????f?=?open('myfile.txt') ????s?=?f.readline() ????i?=?int(s.strip())except?OSError?as?err:????print("OS?error:?{0}".format(err))except?ValueError:????print("Could?not?convert?data?to?an?integer.")except:????print("Unexpected?error:",?sys.exc_info()[0])????raise

      class?B(Exception):????passclass?C(B):????passclass?D(C):????passfor?cls?in?[B,?C,?D]:????try:????????raise?cls()????except?D:????????print("D")????except?C:????????print("C")????except?B:????????print("B")

      Context Manager - with

      with 常用于打開或者關閉某些資源 :

      host?=?'localhost'port?=?5566with?Socket(host,?port)?as?s:????while?True: ????????conn,?addr?=?s.accept() ????????msg?=?conn.recv(1024)????????print?msg ????????conn.send(msg) ????????conn.close()

      單元測試

      from?__future__?import?print_functionimport?unittestdef?fib(n):????return?1?if?n<=2?else?fib(n-1)+fib(n-2)def?setUpModule():????????print("setup?module")def?tearDownModule():????????print("teardown?module")class?TestFib(unittest.TestCase):????def?setUp(self):????????print("setUp")????????self.n?=?10 ????def?tearDown(self):????????print("tearDown")????????del?self.n????@classmethod ????def?setUpClass(cls):????????print("setUpClass")????@classmethod ????def?tearDownClass(cls):????????print("tearDownClass")????def?test_fib_assert_equal(self):????????self.assertEqual(fib(self.n),?55)????def?test_fib_assert_true(self):????????self.assertTrue(fib(self.n)?==?55)if?__name__?==?"__main__": ????unittest.main()

      存儲

      文件讀寫

      路徑處理

      Python 內置的?__file__?關鍵字會指向當前文件的相對路徑,可以根據它來構造絕對路徑,或者索引其他文件 :

      #?獲取當前文件的相對目錄dir?=?os.path.dirname(__file__)?#?src\app##?once?you're?at?the?directory?level?you?want,?with?the?desired?directory?as?the?final?path?node:dirname1?=?os.path.basename(dir) dirname2?=?os.path.split(dir)[1]?##?if?you?look?at?the?documentation,?this?is?exactly?what?os.path.basename?does.#?獲取當前代碼文件的絕對路徑,abspath?會自動根據相對路徑與當前工作空間進行路徑補全os.path.abspath(os.path.dirname(__file__))?#?D:\WorkSpace\OWS\tool\ui-tool-svn\python\src\app#?獲取當前文件的真實路徑os.path.dirname(os.path.realpath(__file__))?#?D:\WorkSpace\OWS\tool\ui-tool-svn\python\src\app#?獲取當前執行路徑os.getcwd()

      可以使用 listdir、walk 、 glob 模塊來進行文件枚舉與檢索:

      #?僅列舉所有的文件from?os?import?listdirfrom?os.path?import?isfile,?join onlyfiles?=?[f?for?f?in?listdir(mypath)?if?isfile(join(mypath,?f))]#?使用?walk?遞歸搜索from?os?import?walk f?=?[]for?(dirpath,?dirnames,?filenames)?in?walk(mypath): ????f.extend(filenames)????break#?使用?glob?進行復雜模式匹配import?globprint(glob.glob("/home/adam/*.txt"))#?['/home/adam/file1.txt',?'/home/adam/file2.txt',?....?]

      簡單文件讀寫

      #?可以根據文件是否存在選擇寫入模式mode?=?'a'?if?os.path.exists(writepath)?else?'w'#?使用?with?方法能夠自動處理異常with?open("file.dat",mode)?as?f: ????f.write(...)????... ????#?操作完畢之后記得關閉文件 ????f.close()#?讀取文件內容message?=?f.read()

      附件: Python-CheatSheet.rar 0 下載次數:0次

      Python 數據結構

      版權聲明:本文內容由網絡用戶投稿,版權歸原作者所有,本站不擁有其著作權,亦不承擔相應法律責任。如果您發現本站中有涉嫌抄襲或描述失實的內容,請聯系我們jiasou666@gmail.com 處理,核實后本網站將在24小時內刪除侵權內容。

      上一篇:excel打開表格程序錯誤的解決方法(excel表格打開遇到錯誤)
      下一篇:通過車載終端的“大考”
      相關文章
      亚洲国产精品免费观看| 亚洲人成网站色在线观看| 亚洲国产高清国产拍精品| 久久精品国产亚洲AV麻豆网站| 日韩亚洲一区二区三区| 亚洲男人的天堂www| 亚洲精品99久久久久中文字幕| 偷自拍亚洲视频在线观看99| 亚洲AV噜噜一区二区三区| 亚洲国产成人久久一区二区三区| 亚洲午夜精品一区二区麻豆| 亚洲人成网站在线播放2019| 亚洲精品无码少妇30P| 午夜亚洲国产理论片二级港台二级 | 亚洲人成人77777在线播放| 亚洲成人福利在线观看| 亚洲不卡中文字幕| 亚洲综合成人婷婷五月网址| 亚洲另类无码专区丝袜| 精品亚洲国产成人av| 亚洲第一福利网站在线观看| 亚洲精品国产高清嫩草影院 | 亚洲精品成人网站在线播放| 亚洲欧洲日本国产| 亚洲五月丁香综合视频| 亚洲色成人WWW永久在线观看| 亚洲变态另类一区二区三区| 国产精品亚洲а∨无码播放麻豆| 国内成人精品亚洲日本语音| 亚洲综合另类小说色区色噜噜| 亚洲精品国产成人片| 亚洲国产精品久久久久| 亚洲女人18毛片水真多| 亚洲综合久久精品无码色欲| 日韩亚洲翔田千里在线| 亚洲午夜久久久久久久久久 | 久久亚洲中文字幕无码| 亚洲一级特黄无码片| 亚洲阿v天堂在线| 亚洲电影免费观看| 亚洲中文字幕无码av|