百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术文章 > 正文

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

itomcoil 2025-01-01 20:54 23 浏览

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

通常,在每个Python项目中,我们都会看到上面的语句。所以它到底是干什么的,我们在这里就要明白了。

简单地说,在Python中,__name__是一个特殊的变量,它告诉我们模块的名称。无论何时直接运行python文件,它都会在执行实际代码之前设置一些特殊变量。__name__是一个特殊变量。根据以下几点确定__name__变量的值-

  1. 如果直接运行python文件,__name__会将该名称设置为main
  2. 如果你将一个模块导入另一个文件中,__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。

所以我们在下面的条件下使用了

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

打开文件

你可以用两种方式打开文件

  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

相关推荐

selenium(WEB自动化工具)

定义解释Selenium是一个用于Web应用程序测试的工具。Selenium测试直接运行在浏览器中,就像真正的用户在操作一样。支持的浏览器包括IE(7,8,9,10,11),MozillaF...

开发利器丨如何使用ELK设计微服务中的日志收集方案?

【摘要】微服务各个组件的相关实践会涉及到工具,本文将会介绍微服务日常开发的一些利器,这些工具帮助我们构建更加健壮的微服务系统,并帮助排查解决微服务系统中的问题与性能瓶颈等。我们将重点介绍微服务架构中...

高并发系统设计:应对每秒数万QPS的架构策略

当面试官问及"如何应对每秒几万QPS(QueriesPerSecond)"时,大概率是想知道你对高并发系统设计的理解有多少。本文将深入探讨从基础设施到应用层面的解决方案。01、理解...

2025 年每个 JavaScript 开发者都应该了解的功能

大家好,很高兴又见面了,我是"高级前端进阶",由我带着大家一起关注前端前沿、深入前端底层技术,大家一起进步,也欢迎大家关注、点赞、收藏、转发。1.Iteratorhelpers开发者...

JavaScript Array 对象

Array对象Array对象用于在变量中存储多个值:varcars=["Saab","Volvo","BMW"];第一个数组元素的索引值为0,第二个索引值为1,以此类推。更多有...

Gemini 2.5编程全球霸榜,谷歌重回AI王座,神秘模型曝光,奥特曼迎战

刚刚,Gemini2.5Pro编程登顶,6美元性价比碾压Claude3.7Sonnet。不仅如此,谷歌还暗藏着更强的编程模型Dragontail,这次是要彻底翻盘了。谷歌,彻底打了一场漂亮的翻...

动力节点最新JavaScript教程(高级篇),深入学习JavaScript

JavaScript是一种运行在浏览器中的解释型编程语言,它的解释器被称为JavaScript引擎,是浏览器的一部分,JavaScript广泛用于浏览器客户端编程,通常JavaScript脚本是通过嵌...

一文看懂Kiro,其 Spec工作流秒杀Cursor,可移植至Claude Code

当Cursor的“即兴编程”开始拖累项目质量,AWS新晋IDEKiro以Spec工作流打出“先规范后编码”的系统工程思维:需求-设计-任务三件套一次生成,文档与代码同步落地,复杂项目不...

「晚安·好梦」努力只能及格,拼命才能优秀

欢迎光临,浏览之前点击上面的音乐放松一下心情吧!喜欢的话给小编一个关注呀!Effortscanonlypass,anddesperatelycanbeexcellent.努力只能及格...

JavaScript 中 some 与 every 方法的区别是什么?

大家好,很高兴又见面了,我是姜茶的编程笔记,我们一起学习前端相关领域技术,共同进步,也欢迎大家关注、点赞、收藏、转发,您的支持是我不断创作的动力在JavaScript中,Array.protot...

10个高效的Python爬虫框架,你用过几个?

小型爬虫需求,requests库+bs4库就能解决;大型爬虫数据,尤其涉及异步抓取、内容管理及后续扩展等功能时,就需要用到爬虫框架了。下面介绍了10个爬虫框架,大家可以学习使用!1.Scrapysc...

12个高效的Python爬虫框架,你用过几个?

实现爬虫技术的编程环境有很多种,Java、Python、C++等都可以用来爬虫。但很多人选择Python来写爬虫,为什么呢?因为Python确实很适合做爬虫,丰富的第三方库十分强大,简单几行代码便可实...

pip3 install pyspider报错问题解决

运行如下命令报错:>>>pip3installpyspider观察上面的报错问题,需要安装pycurl。是到这个网址:http://www.lfd.uci.edu/~gohlke...

PySpider框架的使用

PysiderPysider是一个国人用Python编写的、带有强大的WebUI的网络爬虫系统,它支持多种数据库、任务监控、项目管理、结果查看、URL去重等强大的功能。安装pip3inst...

「机器学习」神经网络的激活函数、并通过python实现激活函数

神经网络的激活函数、并通过python实现whatis激活函数感知机的网络结构如下:左图中,偏置b没有被画出来,如果要表示出b,可以像右图那样做。用数学式来表示感知机:上面这个数学式子可以被改写:...