第十章 文件和异常

  • 文件的读取
    • 整个读取(注:rstrip()方法清楚字符串末尾的空白,strip()方法清除字符串开头的空白)
    • 逐行读取

01 with open('C:\Users\Franz\Desktop\pi_digits.txt') as file_object:

02 contents=file_object.read();#整个读取

03 print(contents.rstrip());#方法rstrip剔除字符串末尾的空白

04

05 with open('C:\Users\Franz\Desktop\pi_digits.txt') as file_object:

06 # 逐行读取

07 print("逐行读取");

08 for line in file_object:

09 print(line.rstrip());

>>>

3.1415926535

8979323846

2643383279

逐行读取

3.1415926535

8979323846

2643383279

  • 创建一个包含文件各行内容的列表(利用方法readlines())

01 with open('C:\Users\Franz\Desktop\pi_million_digits.txt') as file_object:

02 lines = file_object.readlines()

03

04 pi_string = ''

05 for line in lines:

06 pi_string += line.strip()

07 print(pi_string[0:50])

08 print(len(pi_string));

09 birthday = input("Enter your birthday, in the form mmddyy: ")

10 if birthday in pi_string:

11 print("Your birthday appears in the first million digits of pi!")

12 else:

13 print("Your birthday does not appear in the first million digits of pi.")

>>>

3.141592653589793238462643383279502884197169399375

1000002

Enter your birthday, in the form mmddyy: 1231996

Your birthday appears in the first million digits of pi!

  • 文件的写入

    注意:

    • 文本写入文件, 你在调用open() 时需要提供另一个实参, 告诉Python你要写入打开的文件

      实参'w'告诉Python, 我们要以写入模式 打开这个文件。 打开文件时, 可指定读取模式 'r'、 写入模式'w'、附加模式 'a' 或让你能够读取和写入文件的模式'r+'

    • 以写入'w' 模式打开文件时千万要小心, 因为如果指定的文件已经存在,Python将在返回文件对象前清空该文件;写入的文件不存在时,则会重新创建一个文件。
    • Python只能将字符串写入文本文件。 要将数值数据存储到文本文件中, 必须先使用函数str() 将其转换为字符串格式

01 filename = 'programming.txt'

02 with open(filename, 'w') as file_object:

03 file_object.write("I love programming. ");

04 file_object.write("I love creating new games. ");

05

06 """

07 停下查看写入文件,发现上述写入结果:

08 I love programming.

09 I love creating new games.

10 重新以附加模式'a'给文件添加内容,不会覆盖原有的内容,如下是演示示例

11 """

12 identi=input("以附加模式存储文件(是填Yes,否填No):");

13 while identi!='Yes':

14 identi=input("以附加模式存储文件(是填Yes,否填No):");

15 filename = 'programming.txt'

16 with open(filename, 'a') as file_object:

17 file_object.write("I also love finding meaning in the large database. ");

18 file_object.write("I also creating apps that can run in a browser. ");

19 """

20 查看文件的输出结果为:

21 I love programming.

22 I love creating new games.

23 I also love finding meaning in the large database.

24 I also creating apps that can run in a browser.

25 """

  • 异常

    Python使用被称为异常的特殊对象来管理程序执行期间发生的错误。 每当发生让Python不知所措的错误时,它都会创建一个异常对象。

    异常是使用try-except代码块处理的。try-except代码块让Python执行指定的操作,同时告诉Python发生异常时怎么办。使用了try-except 代码块时,即便出现异常,程序也将继续运行:显示你编写的友好的错误消息, 而不是令用户迷惑的traceback。

    try-except-else代码块的工作原理大致如下:Python尝试执行try 代码块中的代码;只有可能引发异常的代码才需要放在try 语句中。有时候,有一些仅在try 代码块成功

    执行时才需要运行的代码;这些代码应放在else代码块中。except代码块告诉Python,如果它尝试运行try 代码块中的代码时引发了指定的异常, 该怎么办。

    • 零除错误(ZeroDivisonError)

01 print("Give me two numbers, and I'll divide them.")

02 print("Enter 'q' to quit.")

03 while True:

04 first_number = input(" First number: ")

05 if first_number == 'q':

06 break

07 second_number = input("Second number: ")

08 try:

09 answer = int(first_number) / int(second_number)

10 except ZeroDivisionError:

11 print("You can't divide by 0!")

12 else:

13 print(answer)

>>>

Give me two numbers, and I'll divide them.

Enter 'q' to quit.

   

First number: 25

Second number: 4

6.25

   

First number: 12

Second number: 0

You can't divide by 0!

   

First number: q

  • FileNotFoundError 异常

    使用方法split() , 它根据一个字符串创建一个单词列表

01 def count_words(filename):

02 """这是一个给英文书籍统计字数的函数"""

03 try:

04 with open(filename) as f_obj:

05 contents = f_obj.read()

06 except FileNotFoundError:

07 msg = "Sorry, the file " + filename + " does not exist."

08 print(msg)

09 else:

10 # 计算文件大致包含多少个单词

11 words = contents.split()

12 num_words = len(words)

13 print("The file " + filename + " has about " + str(num_words) + " words.")

14

15

16 filenames=['alice.txt','sidehartha.txt','moby_dick.txt','little_women.txt'];

17 for filename in filenames:

18 count_words(filename);

>>>

The file alice.txt has about 29461 words.

Sorry, the file sidehartha.txt does not exist.

The file moby_dick.txt has about 215136 words.

The file little_women.txt has about 189079 words.

  • 运行异常时不报任何错误

    在except代码块中利用pass语句明确地告诉Python什么都不要做。以上述为例

01 def count_words(filename):

02 """这是一个给英文书籍统计字数的函数"""

03 try:

04 with open(filename) as f_obj:

05 contents = f_obj.read()

06 except FileNotFoundError:

07 pass #利用关键词pass跳过错误反馈部分

08 else:

09 # 计算文件大致包含多少个单词

10 words = contents.split()

11 num_words = len(words)

12 print("The file " + filename + " has about " + str(num_words) + " words.")

13

14

15 filenames=['alice.txt','sidehartha.txt','moby_dick.txt','little_women.txt'];

16 for filename in filenames:

17 count_words(filename);

>>>

The file alice.txt has about 29461 words.

The file moby_dick.txt has about 215136 words.

The file little_women.txt has about 189079 words.

  • 存储数据

    用户关闭程序时, 要保证高度的保存储存他们提供的信息; 一种简单的方式是使用模块json 来存储数据

    • 函数json.dump(variable,filename) 接受两个实参: 要存储的数据以及可用于存储数据的文件对象。
    • 函数json.load(filename)

01 import json

02 # 如果存储了用户名,则加载它

03 # 如果未存储,则输入用户名并进行存储

04 filename='username.json';

05 try:

06 with open(filename) as f_obj:

07 username=json.load(f_obj);

08 except FileNotFoundError:

09 username=input("what is your name?");

10 with open(filename,'w') as f_obj:

11 json.dump(username,f_obj);

12 print("We'll remember you when you come back,"+username+'!');

13 else:

14 print("Welcome back, "+username+"!");

>>>

Welcome back, Franz!

  • 重构

    代码能够正确地运行, 但可做进一步的改进——将代码划分为一系列完成具体工作的函数。这样的过程被称为重构

    重构让代码更清晰、 更易于理解、 更容易扩展。

       

       

       

       

       

       

       

       

       

       

       

       

       

       

       

为更美好的明天而战!!!
原文地址:https://www.cnblogs.com/lovely-bones/p/11013394.html