文件和异常

文件

文件读取

  1. 读取整个文件

创建一个名为pi.txt的文件

文件内容

3.1415926535
  8979323846
  2643383279

主程序:

#使用with语句和open函数读取文件
#with语句通常用于异常处理,在处理文件对象时非常棒
#open("文件路径",写入模式),写入模式有:1、只读模式"r",2、写入模式"w",3、附加模式"a",4、读写模式"r+"
#使用read()方法读取文件对象内容
with open("pi.txt","r") as pi:
    contents = pi.read()
print(contents)

OUT:

3.1415926535
  8979323846
  2643383279
  

相比原文件会多出来一个换行符

使用rstrip()方法可解决问题

with open("pi.txt","r") as pi:
    contents = pi.read()
print(contents.rstrip())

OUT:

3.1415926535
  8979323846
  2643383279

2.逐行读取

  • 对文件对象使用for循环

    with open("pi.txt") as pi:
        for line in pi:
            print(line)
    

    OUT:

    3.1415926535
    
      8979323846
    
      2643383279
  • 使用readlines()方法

    #readlines()方法会将文件对象逐行读取并放入列表中
    with open("pi.txt") as pi:
        for line in pi.readlines():
            print(line)
    
    with open("pi.txt") as pi: 
        print(pi.readlines())

    OUT:

    3.1415926535
    
      8979323846
    
      2643383279
    ['3.1415926535\n', '  8979323846\n', '  2643383279']

写入文件

  1. 擦除原文件并写入

    #使用write()方法写入内容
    with open("pi.txt",'w') as pi:
        pi.write("3.14")

    此时没有输出,打开pi.txt文件

    pi.txt

    3.14
  2. 附加到原文件

    #使用write()方法写入内容
    with open("pi.txt",'a') as pi:
        pi.write("\n3.14")

    此时没有输出,打开pi.txt文件

    pi.txt

    3.14
    3.14

异常

python使用称为异常的对象处理程序执行期间发生的错误,如果未对异常进行处理,程序将停止运行并显示traceback

使用try-excpet-else-finally处理异常

常见异常

>>> 10 * (1/0)             # 0 不能作为除数,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ZeroDivisionError: division by zero
>>> 4 + spam*3             # spam 未定义,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
NameError: name 'spam' is not defined
>>> '2' + 2               # int 不能与 str 相加,触发异常
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str

该文本来自菜鸟教程

语法

try:
    可能会异常的代码
except:
    发生异常时执行的代码
else:
    没有异常时执行的代码
finally:
    不管有没有异常都会执行的代码
try:
    print(5/0)
except ZeroDivisionError:
    print("0不能做除数")
finally:
    print("end")

OUT:

0不能做除数
end

如果不这么做会怎样

print(5/0)
print("0不能做除数")
print("end")

OUT:

Traceback (most recent call last):
  File "C:/Users/19736/Desktop/a.py", line 1, in <module>
    print(5/0)
ZeroDivisionError: division by zero

抛出了ZeroDivisionError错误异常

最后修改:2022 年 05 月 15 日
如果觉得我的文章对你有用,请随意赞赏