从文件中读取数据

1
2
3
with open('pi.txt') as file_object:
contents = file_object.read()
print(contents)
3.1415926535  
  8979323846  
  2643383279

文件路径

  • 绝对路径
  • 相对路径(可以使用r""原始字符串、或者使用双反斜杠\\替代单斜杠\
1
2
3
4
file_name = r"pi.txt"
with open(file_name) as file_object:
contents = file_object.read()
print(contents)
3.1415926535  
  8979323846  
  2643383279
1
2
3
4
# 逐行读取数据
with open(file_name) as file_object:
for line in file_object:
print(line)
3.1415926535  

  8979323846  

  2643383279

readlines()从文件中读取每一行,并将其存储在一个列表中

1
2
3
4
with open(file_name) as file_object: 
lines = file_object.readlines()

print(lines)
['3.1415926535  \n', '  8979323846  \n', '  2643383279']
1
2
3
4
5
6
7
8
9
10
11
12
'''
使用文件的内容
'''
with open(file_name) as file_object:
lines = file_object.readlines()

pi_string = ''
for line in lines:
pi_string += line.strip()

print(pi_string)
print(len(pi_string))
3.141592653589793238462643383279
32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
'''
圆周率值中包含你的生日吗
'''
file_name = 'pi_10000.txt'
with open(file_name) as file_object:
lines = file_object.readlines()

pi_string = ''
for line in lines:
pi_string += line.strip()

birthday = input("Enter your birthday, in the form mmddyy:")
if birthday in pi_string:
print("Your birthday appears in the first million digits of pi!")
else:
print("Your birthday does not appear in the first million digits of pi.")
Enter your birthday, in the form mmddyy: 040413

Your birthday does not appear in the first million digits of pi.

写入文件

读取模式r、写入模式w、附加模式a或让你能够读取和写入文件的模式r+

1
2
3
4
filename = 'programming.txt'

with open(filename, 'w') as file_object:
file_object.write("I love programming.")

异常

  • 异常合集Expection 万物皆可用

处理ZeroDivisionError异常

1
print(5/0)
---------------------------------------------------------------------------

ZeroDivisionError                         Traceback (most recent call last)

Cell In[13], line 1
----> 1 print(5/0)

ZeroDivisionError: division by zero

使用try-except代码块

1
2
3
4
try: 
print(5/0)
except ZeroDivisionError:
print("You can't divide by zero!")
You can't divide by zero!

else 代码块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
print("Give me two numbers, and I'll divide them.")
print("Enter 'q' to quit.")

while True:
first_number = input("\nFirst number: ")
if first_number == 'q':
break

second_number = input("Second number: ")
try:
answer = int(first_number) / int(second_number)
except ZeroDivisionError:
print("You can't divide by 0!")
else:
print("The result is:", answer)
Give me two numbers, and I'll divide them.
Enter 'q' to quit.

First number:  5
Second number:  0

You can't divide by 0!
  
First number:  5
Second number:  2

The result is: 2.5

First number:  q

分析文本

1
2
title = "Alice in Wonderland"  
title.split()
['Alice', 'in', 'Wonderland']
1
2
3
4
5
6
7
8
9
10
11
12
file_name = 'alice1.txt'

try:
with open(file_name) as f:
contents = f.read()
except FileNotFoundError:
msg = "Sorry, the file " + file_name + " does not exist."
print(msg)
else:
words = contents.split()
num_words = len(words)
print(f"The file {file_name} has about {str(num_words)} words.")
Sorry, the file alice1.txt does not exist.
1
2
3
4
5
6
7
8
9
10
11
12
file_name = 'alice.txt'

try:
with open(file_name, encoding='utf-8') as f:
contents = f.read()
except FileNotFoundError:
msg = "Sorry, the file " + file_name + " does not exist."
print(msg)
else:
words = contents.split()
num_words = len(words)
print(f"The file {file_name} has about {str(num_words)} words.")
The file alice.txt has about 17868 words.

失败时一声不吭pass

1
2
3
4
5
6
7
8
9
10
11
file_name = 'alice1.txt'

try:
with open(file_name) as f:
contents = f.read()
except FileNotFoundError:
pass
else:
words = contents.split()
num_words = len(words)
print(f"The file {file_name} has about {str(num_words)} words.")

存储数据

  • json.dump() 存储数据
  • json.load() 加载数据
1
2
3
4
5
6
7
import json 

numbers = [2, 3, 5, 7, 11, 13]

filename = 'numbers.json'
with open(filename, 'w') as f_obj:
json.dump(numbers, f_obj)
1
2
3
4
5
6
7
import json 

filename = 'numbers.json'
with open(filename) as f_obj:
numbers = json.load(f_obj)

print(numbers)
[2, 3, 5, 7, 11, 13]

保存和读取用户生成的数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import json

# 如果以前存储了用户名,就加载它
# 否则,就提示用户输入用户名并存储它

filename = 'username.json'

try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name? ")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back, " + username + "!")
else:
print("Welcome back, " + username + "!")
What is your name?  kj

We'll remember you when you come back, kj!

重构

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import json 

def greet_user():
"""问候用户,并指出其名字"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
username = input("What is your name? ")
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
print("We'll remember you when you come back, " + username + "!")
else:
print("Welcome back, " + username + "!")

greet_user()
Welcome back, kj!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import json 

def get_stored_username():
"""如果存储了用户名,就获取它"""
filename = 'username.json'
try:
with open(filename) as f_obj:
username = json.load(f_obj)
except FileNotFoundError:
return None
else:
return username

def get_new_username():
"""提示用户输入用户名"""
username = input("What is your name? ")
filename = 'username.json'
with open(filename, 'w') as f_obj:
json.dump(username, f_obj)
return username

def greet_user():
"""问候用户,并指出其名字"""
username = get_stored_username()
if username:
print("Welcome back, " + username + "!")
else:
username = get_new_username()
print("We'll remember you when you come back, " + username + "!")

greet_user()
Welcome back, kj!

在本章中,你学习了:如何使用文件;如何一次性读取整个文件,以及如何以每次一行的方式读取文件的内容;如何写入文件,以及如何将文本附加到文件末尾;什么是异常以及如何处理程序可能引发的异常;如何存储Python数据结构,以保存用户提供的信息,避免用户每次运行程序时都需要重新提供。