Python中的文件和异常

本文最后更新于 2025年10月30日 下午

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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# 文件的读取与使用

from pathlib import Path

path = Path('pi_digital.txt')
content = path.read_text().rstrip()
print(content)

content_split = content.splitlines()

pi_string = ''

for line in content_split:
pi_string += line

print(pi_string)

pi_string = ''

for line in content_split:
pi_string += line.lstrip()

print(pi_string)

# 对于异常的处理

# try-except 代码块会告诉python如何处理异常,如果你不做处理,程序会停止运行并返回traceback

# division_calculator

def division_calculator(a,b):
try:
print(a/b)
except:
print('You are trying to divide by zero!')
# division_calculator(5/0)

## r"""禁用转义

r"""
Traceback (most recent call last):
File "c:\Users\onlym\Documents\code\python_works\fundemental\file_and_error\error.py", line 10, in <module>
division_calculator(5/0)
~^~
ZeroDivisionError: division by zero
"""

# 但是如果这样写:

r'''
try:
division_calculator(5/0)

except:
print('You are trying to divide by zero!')

'''

division_calculator(5,0)


#这样可以避免出现python的难以阅读的报错

# FileNotFoundError

from pathlib import Path

path = Path('non_existent_file.txt')

try:
content = path.read_text(encoding='utf-8')
except FileNotFoundError:
print('The file does not exist!')

# 分析文本

# 使用函数split(),其默认以空格将字符串查分成多个部分

else:
words = content.split()
num_words = len(words)
print(f'The file {path} has about {num_words} words.')

# 使用多个文件

def count_words(path):
try:
content = path.read_text(encoding = 'utf-8')
except:
print('Sorry, the file {path} does not exist.')
else:
words = content.split()
num_words = len(words)
print(f'The file {path} has about {num_words} words.')



from pathlib import Path
path = Path('test_write.txt')
path.write_text('Hello, World!\nThis is a test file.\nHave a great day!')

## 存入多行到文件中

contents = 'I love programing.\n'
contents += 'I love sloving alogrithm problems!\n'
contents += 'I love learning!'

path_2 = Path('programing.txt')
path_2.write_text(contents)

# wirte_text函数会删除原本的内容

from pathlib import Path
import json

# def greet_user():
# '''问候用户'''
# path = Path('username.json')
# if path.exists():
# content = path.read_text()
# username = json.loads(content)
# print(f'Welcome back, {username}!')
# else:
# '''如果没有,就记录username'''
# username = input("Please input your username:")
# content = json.dumps(username)
# path.write_text(content)


def get_stored_username(path):
'''如果储存了用户名,就获取'''
if path.exists():
content = path.read_text()
username = json.loads(content)
return username
else:
return None

def greet_user():
'''问候用户'''
path = Path('username.json')
username = get_stored_username(path)
if username != None:
print(f"Welcome back {username}!")
else:
get_start_username()

def get_start_username():
'''获取新的用户名'''
path = Path('username.json')
username = input("Please input your username:")
content = json.dumps(username)
path.write_text(content)
print("We'll remember you next time!")

greet_user()

from pathlib import Path
import json

number = [10,9,8,7,6,5,4,3,2,1]

path = Path('number.json')
contents = json.dumps(number)
path.write_text(contents)

from pathlib import Path
import json

username = input("What's your name?")

path = Path('username.json')
contents = json.dumps(username)
path.write_text(contents)

print(f"We'll remember you when you come back, {username}")

from pathlib import Path
import json

path = Path('username.json')
content = path.read_text()
username = json.loads(content)

print(f'Welcome back, {username}!')


Python中的文件和异常
https://www.mirstar.net/2025/10/23/Python-3-file-and-error/
作者
onlymatt
发布于
2025年10月23日
许可协议