Python教程:文件、异常处理和其余

做者|Vishal Mishra
编译|VK
来源|Towards Data Sciencehtml

欢迎阅读Python教程。在本章中,咱们将学习文件、异常处理和其余一些概念。咱们开始吧。python

__name__ == '__main__'是什么意思?git

一般,在每一个Python项目中,咱们都会看到上面的语句。因此它究竟是干什么的,咱们在这里就要明白了。github

简单地说,在Python中,__name__是一个特殊的变量,它告诉咱们模块的名称。不管什么时候直接运行python文件,它都会在执行实际代码以前设置一些特殊变量。__name__是一个特殊变量。根据如下几点肯定__name__变量的值-编程

  1. 若是直接运行python文件,__name__会将该名称设置为main
  2. 若是你将一个模块导入另外一个文件中,__name__会将该名称设置为模块名。
__name__

'__main__'

first_module.py. 直接运行机器学习

first_module.py从其余模块导入编程语言

输出ide

In first_module.py, Running from Import

In second_module.py. Second module’s name: main

上面的示例中,你能够看到,当你在另外一个python文件中导入第一个模块时,它将进入else条件,由于模块的名称不是main。可是,在second_module.py,名字仍然是main。函数

因此咱们在下面的条件下使用了oop

  1. 当咱们想执行某些特定任务时,咱们能够直接调用这个文件。
  2. 若是模块被导入到另外一个模块中,而咱们不想执行某些任务时。

最好是建立一个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块中处理多个异常。你能够有两种方法-

  1. 在同一行中提供不一样的异常。示例:ZeroDivisionError,NameError :
  2. 提供多个异常块。当你但愿为每一个异常提供单独的异常消息时,这颇有用。示例:
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/l...

如何处理文件

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

打开文件

你能够用两种方式打开文件

  1. 定义一个包含file对象的变量。在处理完一个文件以后,咱们必须使用file对象方法close再次关闭它:

    f = open("demo_text_file.txt", "r")
    ---
    f.close()
  2. 使用with关键字。不须要显式关闭文件。

    with open(“demo_text_file.txt”, “r”): 
        ##读取文件

在open方法中,咱们必须传递定义文件访问模式的第二个参数。“r”是用来读文件的。相似地,“w”表示写入,“a”表示附加到文件。在下表中,你能够看到更经常使用的文件访问模式。

读取文件

在python中,有多种方法能够读取一个文件-

  1. fileObj.read()=>将把整个文件读入字符串。
  2. fileObj.readline() =>将逐行读取文件。
  3. 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种写入文件的方法。

  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:
        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/

相关文章
相关标签/搜索