作者|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 ImportIn 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: 5Sqaure 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: fiveLooks like you did not enter an integer!Try again-Please enter an integer: 4Finally, 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: sixLooks like you did not enter an integer!Please enter an integer: fiveLooks like you did not enter an integer!Please enter an integer: fourLooks like you did not enter an integer!Please enter an integer: 7Yepie...you enterted integer finally so breaking out of the loopSqaure 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: 5Enter second number: 0Divide by zero exception occured! Try Again! division by zeroProgram ended.
如何创立自定义异样
有可能创立本人的异样。你能够用raise关键字来做。
创立自定义异样的最佳办法是创立一个继承默认异样类的类。
这就是Python中的异样解决。你能够在这里查看内置异样的残缺列表:https://docs.python.org/3.7/l...
如何解决文件
Python中的文件解决
Python应用文件对象与计算机上的内部文件进行交互。这些文件对象能够是你计算机上的任何文件格式,即能够是音频文件、图像、文本文件、电子邮件、Excel文档。你可能须要不同的库来解决不同的文件格式。
让咱们应用ipython命令创立一个简略的文本文件,咱们将理解如何在Python中读取该文件。
%%writefile demo_text_file.txthello worldi love ipythonjupyter notebookfourth linefifth linesix lineThis is the last line in the fileWriting 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 worldi love ipythonjupyter notebookfourth linefifth linesix lineThis is the last line in the file------- reading file line by line --------printing only first 2 lineshello worldi 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 worldi love ipythonjupyter notebookfourth linefifth linesix lineThis 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...
原文链接:https://towardsdatascience.co...
欢送关注磐创AI博客站:
http://panchuang.net/
sklearn机器学习中文官网文档:
http://sklearn123.com/
欢送关注磐创博客资源汇总站:
http://docs.panchuang.net/