Python tutorials: files, exception handling, and more

python tutorials files exception handling

author |Vishal Mishra
compile |VK
source |Towards Data Science

Welcome to Python course . In this chapter , We are going to study the document 、 Exception handling and other concepts . Let's start .

__name__ == '__main__' What does that mean? ?

Usually , At every Python In the project , We'll all see the above statement . So what is it for , We are here to understand .

In short , stay Python in ,__name__ It's a special variable , It tells us the name of the module . Whenever it runs directly python file , It sets special variables before executing the actual code .__name__ It's a special variable . Determine according to the following points __name__ The value of the variable -

  1. If it runs directly python file ,__name__ The name will be set to main.

  2. If you import a module into another file ,__name__ The name will be set to the module name .

'__main__' Direct operation Import from other modules


In, Running from Import
In Second module’s name: main

In the example above , You can see , When you're in another python When the first module is imported into the file , It will enter else Conditions , Because the name of the module is not main. however , stay, The name is still main.

So we use it under the following conditions

  1. When we want to perform certain specific tasks , We can call this file directly .

  2. If the module is imported into another module , And when we don't want to perform certain tasks .

It's best to create a main Method , And in if __name__ == __main__ Internal calls . therefore , if necessary , You can still call from another module main Method .

We can still call main Method to call another module's main Method , because main Methods should exist in the first module .

What to do if something goes wrong

Python Exception handling in

When we write any program in any programming language , Sometimes even if the statement or expression is syntactically correct , There are also errors in the execution process . Errors detected during the execution of any program are called exceptions .

Python The basic terminology and syntax used to handle errors in is try and except sentence . Code that can cause an exception to occur is placed in try In block , Exception handling in except Implementation in block .python The syntax for handling exceptions in is as follows -

try and except

Do your operation …
except ExceptionI:
If there is any abnormality ExceptionI, Execute this block .
except ExceptionII:
If there is any abnormality ExceptionII, Execute this block .
If there is no abnormality , Then execute this block .
No matter whether there is any abnormality , This block will always execute

Let's use an example to understand this . In the following example , I'm going to create a function to square numbers , In order to calculate the square , The function should always accept a number ( In this case, it's an integer ). But the user doesn't know about him / What kind of input does she need to provide . When the user enters a number , It works well , But if the user provides a string instead of a number , What's going to happen .

def acceptInput():
num = int(input("Please enter an integer: "))
print("Sqaure of the the number {} is {}".format(num, num*num))
Please enter an integer: 5
Sqaure of the the number 5 is 25

It throws an exception , The program suddenly ended . therefore , To execute programs gracefully , We need to handle exceptions . Let's look at the following example -

def acceptInput():
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: "))
print("Finally, I executed!")
print("Sqaure of the the number {} is {}".format(num, num*num))
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

such , And we can provide logic for handling exceptions . But in the same example , If the user enters a string value again . What will happen then ?

So in this case , It's best to enter... In a loop , Until the user enters a number .

def acceptInput():
while True:
num = int(input("Please enter an integer: "))
except ValueError:
print("Looks like you did not enter an integer!")
print(" enterted integer finally so breaking out of the loop")
print("Sqaure of the the number {} is {}".format(num, num*num))
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 enterted integer finally so breaking out of the loop
Sqaure of the the number 7 is 49

How to handle multiple exceptions

Can be in the same try except Block to handle multiple exceptions . You can have two ways -

  1. Provide different exceptions on the same line . Example :ZeroDivisionError,NameError :

  2. Provides multiple exception blocks . When you want to provide a separate exception message for each exception , It's very useful . Example :

except ZeroDivisionError as e:
print(“Divide by zero exception occurred!, e)
except NameError as e:
print(“NameError occurred!, e)

Include at the end except Exception:block It's always good , You can catch any unwanted exceptions you don't know about . This is a general exception capture command , It will cause any type of exception in the code .

# Handle multiple exceptions
def calcdiv():
x = input("Enter first number: ")
y = input("Enter second number: ")
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)
print("Program ended.")
Enter first number: 5
Enter second number: 0
Divide by zero exception occured! Try Again! division by zero
Program ended.

How to create a custom exception

It's possible to create your own exceptions . You can use it. raise Keywords to do .

The best way to create a custom exception is to create a class that inherits the default exception class .

This is it. Python Exception handling in . You can see a complete list of built-in exceptions here :

How to deal with documents

Python File processing in

Python Use file objects to interact with external files on your computer . These file objects can be any file format on your computer , It can be an audio file 、 Images 、 text file 、 E-mail 、Excel file . You may need different libraries to handle different file formats .

Let's use ipython Command to create a simple text file , We'll learn how to do it in Python Read from the file .

%%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

Open file

You can open a file in two ways

  1. Define an inclusion file Object's variables . After processing a file , We have to use file Object methods close Turn it off again :

    f = open("demo_text_file.txt", "r")
  2. Use with keyword . There is no need to explicitly close the file .

    with open(“demo_text_file.txt”, “r”):
    ## Read the file

stay open In the method , We have to pass the second parameter that defines the file access pattern .“r” It's for reading files . Similarly ,“w” Means write ,“a” Indicates that it is attached to a file . In the table below , You can see more common file access patterns .

Read the file

stay python in , There are many ways to read a file -

  1.> The entire file will be read into the string .

  2. fileObj.readline() => The file will be read line by line .

  3. fileObj.readlines()=> The entire file will be read and a list will be returned . Use this method with care , Because this will read the entire file , So the file size should not be too large .

# Read entire file
print("------- reading entire file --------")
with open("demo_text_file.txt", "r") as f:
# Read the file line by line
print("------- reading file line by line --------")
print("printing only first 2 lines")
with open("demo_text_file.txt", "r") as f:
# Read the file and return it as a list
print("------- reading entire file as a list --------")
with open("demo_text_file.txt", "r") as f:
# Use for Loop read file
print("\n------- reading file with a for loop --------")
with open("demo_text_file.txt", "r") as f:
for lines in f:
------- 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

Writing documents

And read similar ,python The following are provided 2 A way to write a file .

  1. fileObj.write()

  2. fileObj.writelines()

with open("demo_text_file.txt","r") as f_in:
with open("demo_text_file_copy.txt", "w") as f_out:

Read write binary

You can use binary mode to read and write any image file . Binary contains data in byte format , This is the recommended way to process images . Remember to use binary mode , With “rb” or “wb” Mode open file .

with open("cat.jpg","rb") as f_in:
with open("cat_copy.jpg", "wb") as f_out:
print("File copied...")
File copied...

Sometimes when the file is too large , Block reading is recommended ( Read fixed bytes at a time ), In this way, there will be no out of memory exceptions . You can provide any value for the block size . In the following example , You'll see how to read a file in a block and write to another file .

### Copy the image with a block
with open("cat.jpg", "rb") as img_in:
with open("cat_copy_2.jpg", "wb") as img_out:
chunk_size = 4096
img_chunk =
while len(img_chunk) > 0:
img_chunk =
print("File copied with chunks")
File copied with chunks


Now you know how to do exception handling and how to use Python Documents in .

Here is Jupyter Notebook Link to :

Link to the original text :

Welcome to join us AI Blog station :

sklearn Machine learning Chinese official documents :

Welcome to pay attention to pan Chuang blog resource summary station :

本文为[Artificial intelligence meets pioneer]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database