# Python中的文件和异常

Canonical: https://www.mirstar.net/2025/10/23/Python-3-file-and-error/
Author: onlymatt
Published: 2025-10-23T04:30:38.000Z
Updated: 2026-10-21T11:21:55.779Z
Categories: Programming, Python
Tags: File Handling, Exception Handling

```
# 文件的读取与使用

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}!')

```
