作者|Vishal Mishra
編譯|VK
來源|Towards Data Science
歡迎閱讀Python教程,在本章中,我們將學習檔案、例外處理和其他一些概念,我們開始吧,

__name__ == '__main__'是什么意思?
通常,在每個Python專案中,我們都會看到上面的陳述句,所以它到底是干什么的,我們在這里就要明白了,
簡單地說,在Python中,__name__是一個特殊的變數,它告訴我們模塊的名稱,無論何時直接運行python檔案,它都會在執行實際代碼之前設定一些特殊變數,__name__是一個特殊變數,根據以下幾點確定__name__變數的值-
-
如果直接運行python檔案,
__name__會將該名稱設定為main, -
如果你將一個模塊匯入另一個檔案中,
__name__會將該名稱設定為模塊名,
__name__
'__main__'
first_module.py. 直接運行

first_module.py從其他模塊匯入

輸出
In first_module.py, Running from Import
In second_module.py. Second module’s name: main
上面的示例中,你可以看到,當你在另一個python檔案中匯入第一個模塊時,它將進入else條件,因為模塊的名稱不是main,但是,在second_module.py,名字仍然是main,
所以我們在下面的條件下使用了
-
當我們想執行某些特定任務時,我們可以直接呼叫這個檔案,
-
如果模塊被匯入到另一個模塊中,而我們不想執行某些任務時,
最好是創建一個main方法,并在if __name__ == __main__內部呼叫,因此,如果需要,你仍然可以從另一個模塊呼叫main方法,


我們仍然可以通過顯式呼叫main方法來呼叫另一個模塊的main方法,因為main方法應該存在于第一個模塊中,

出了問題怎么辦
Python中的例外處理
當我們用任何編程語言撰寫任何程式時,有時即使陳述句或運算式在語法上是正確的,也會在執行程序中出錯,在任何程式執行程序中檢測到的錯誤稱為例外,
Python中用于處理錯誤的基本術語和語法是try和except陳述句,可以導致例外發生的代碼放在try塊中,例外的處理在except塊中實作,python中處理例外的語法如下-
try 和except
try:
做你的操作…
...
except ExceptionI:
如果有例外ExceptionI,執行這個塊,
except ExceptionII:
如果有例外ExceptionII,執行這個塊,
...
else:
如果沒有例外,則執行此塊,
finally:
無論是否有例外,此塊都將始終執行
讓我們用一個例子來理解這一點,在下面的示例中,我將創建一個計算數字平方的函式,以便計算平方,該函式應始終接受一個數字(本例中為整數),但是用戶不知道他/她需要提供什么樣的輸入,當用戶輸入一個數字時,它作業得很好,但是如果用戶提供的是字串而不是數字,會發生什么情況呢,
def acceptInput():
num = int(input("Please enter an integer: "))
print("Sqaure of the the number {} is {}".format(num, num*num))
acceptInput()
Please enter an integer: 5
Sqaure of the the number 5 is 25

它拋出一個例外,程式突然結束,因此,為了優雅地執行程式,我們需要處理例外,讓我們看看下面的例子-
def acceptInput():
try:
num = int(input("Please enter an integer: "))
except ValueError:
print("Looks like you did not enter an integer!")
num = int(input("Try again-Please enter an integer: "))
finally:
print("Finally, I executed!")
print("Sqaure of the the number {} is {}".format(num, num*num))
acceptInput()
Please enter an integer: five
Looks like you did not enter an integer!
Try again-Please enter an integer: 4
Finally, I executed!
Sqaure of the the number 4 is 16
這樣,我們就可以提供邏輯并處理例外,但在同一個例子中,如果用戶再次輸入字串值,那會發生什么?

所以在這種情況下,最好在回圈中輸入,直到用戶輸入一個數字,
def acceptInput():
while True:
try:
num = int(input("Please enter an integer: "))
except ValueError:
print("Looks like you did not enter an integer!")
continue
else:
print("Yepie...you enterted integer finally so breaking out of the loop")
break
print("Sqaure of the the number {} is {}".format(num, num*num))
acceptInput()
Please enter an integer: six
Looks like you did not enter an integer!
Please enter an integer: five
Looks like you did not enter an integer!
Please enter an integer: four
Looks like you did not enter an integer!
Please enter an integer: 7
Yepie...you enterted integer finally so breaking out of the loop
Sqaure of the the number 7 is 49
如何處理多個例外
可以在同一個try except塊中處理多個例外,你可以有兩種方法-
-
在同一行中提供不同的例外,示例:ZeroDivisionError,NameError :
-
提供多個例外塊,當你希望為每個例外提供單獨的例外訊息時,這很有用,示例:
except ZeroDivisionError as e:
print(“Divide by zero exception occurred!, e)
except NameError as e:
print(“NameError occurred!, e)
在末尾包含except Exception:block總是很好的,可以捕捉到你不知道的任何不需要的例外,這是一個通用的例外捕捉命令,它將在代碼中出現任何型別的例外,
# 處理多個例外
def calcdiv():
x = input("Enter first number: ")
y = input("Enter second number: ")
try:
result = int(x) / int(y)
print("Result: ", result)
except ZeroDivisionError as e:
print("Divide by zero exception occured! Try Again!", e)
except ValueError as e:
print("Invalid values provided! Try Again!", e)
except Exception as e:
print("Something went wrong! Try Again!", e)
finally:
print("Program ended.")
calcdiv()
Enter first number: 5
Enter second number: 0
Divide by zero exception occured! Try Again! division by zero
Program ended.

如何創建自定義例外
有可能創建自己的例外,你可以用raise關鍵字來做,

創建自定義例外的最佳方法是創建一個繼承默認例外類的類,

這就是Python中的例外處理,你可以在這里查看內置例外的完整串列:https://docs.python.org/3.7/library/exceptions.html
如何處理檔案
Python中的檔案處理
Python使用檔案物件與計算機上的外部檔案進行互動,這些檔案物件可以是你計算機上的任何檔案格式,即可以是音頻檔案、影像、文本檔案、電子郵件、Excel檔案,你可能需要不同的庫來處理不同的檔案格式,
讓我們使用ipython命令創建一個簡單的文本檔案,我們將了解如何在Python中讀取該檔案,
%%writefile demo_text_file.txt
hello world
i love ipython
jupyter notebook
fourth line
fifth line
six line
This is the last line in the file
Writing demo_text_file.txt
打開檔案
你可以用兩種方式打開檔案
-
定義一個包含file物件的變數,在處理完一個檔案之后,我們必須使用file物件方法close再次關閉它:
f = open("demo_text_file.txt", "r") --- f.close() -
使用with關鍵字,不需要顯式關閉檔案,
with open(“demo_text_file.txt”, “r”): ##讀取檔案
在open方法中,我們必須傳遞定義檔案訪問模式的第二個引數,“r”是用來讀檔案的,類似地,“w”表示寫入,“a”表示附加到檔案,在下表中,你可以看到更常用的檔案訪問模式,

讀取檔案
在python中,有多種方法可以讀取一個檔案-
-
fileObj.read()=>將把整個檔案讀入字串,
-
fileObj.readline() =>將逐行讀取檔案,
-
fileObj.readlines()=>將讀取整個檔案并回傳一個串列,小心使用此方法,因為這將讀取整個檔案,因此檔案大小不應太大,
# 讀取整個檔案
print("------- reading entire file --------")
with open("demo_text_file.txt", "r") as f:
print(f.read())
# 逐行讀取檔案
print("------- reading file line by line --------")
print("printing only first 2 lines")
with open("demo_text_file.txt", "r") as f:
print(f.readline())
print(f.readline())
# 讀取檔案并以串列形式回傳
print("------- reading entire file as a list --------")
with open("demo_text_file.txt", "r") as f:
print(f.readlines())
# 使用for回圈讀取檔案
print("\n------- reading file with a for loop --------")
with open("demo_text_file.txt", "r") as f:
for lines in f:
print(lines)
------- reading entire file --------
hello world
i love ipython
jupyter notebook
fourth line
fifth line
six line
This is the last line in the file
------- reading file line by line --------
printing only first 2 lines
hello world
i love ipython
------- reading entire file as a list --------
['hello world\n', 'i love ipython\n', 'jupyter notebook\n', 'fourth line\n', 'fifth line\n', 'six line\n', 'This is the last line in the file\n']
------- reading file with a for loop --------
hello world
i love ipython
jupyter notebook
fourth line
fifth line
six line
This is the last line in the file
寫檔案
與read類似,python提供了以下2種寫入檔案的方法,
-
fileObj.write()
-
fileObj.writelines()
with open("demo_text_file.txt","r") as f_in:
with open("demo_text_file_copy.txt", "w") as f_out:
f_out.write(f_in.read())
讀寫二進制檔案
你可以使用二進制模式來讀寫任何影像檔案,二進制包含位元組格式的資料,這是處理影像的推薦方法,記住使用二進制模式,以“rb”或“wb”模式打開檔案,
with open("cat.jpg","rb") as f_in:
with open("cat_copy.jpg", "wb") as f_out:
f_out.write(f_in.read())
print("File copied...")
File copied...
有時當檔案太大時,建議使用塊進行讀取(每次讀取固定位元組),這樣就不會出現記憶體不足例外,可以為塊大小提供任何值,在下面的示例中,你將看到如何讀取塊中的檔案并寫入另一個檔案,
### 用塊復制影像
with open("cat.jpg", "rb") as img_in:
with open("cat_copy_2.jpg", "wb") as img_out:
chunk_size = 4096
img_chunk = img_in.read(chunk_size)
while len(img_chunk) > 0:
img_out.write(img_chunk)
img_chunk = img_in.read(chunk_size)
print("File copied with chunks")
File copied with chunks
結論
現在你知道了如何進行例外處理以及如何使用Python中的檔案,
下面是Jupyter Notebook的鏈接:https://github.com/vishal2505/PythonByExample/blob/main/Python_Essentials_Part_3.ipynb
原文鏈接:https://towardsdatascience.com/python-essentials-part-3-5b61c1c25b9d
歡迎關注磐創AI博客站:
http://panchuang.net/
sklearn機器學習中文官方檔案:
http://sklearn123.com/
歡迎關注磐創博客資源匯總站:
http://docs.panchuang.net/
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/209909.html
標籤:其他
下一篇:TCP流量控制原理
