Python之文件读取、写入和异常处理操作举例

# 文件读取、写入和异常处理操作举例
# 带参数encoding='utf-8'可解决UnicodeDecodeError编码问题

###### 基础方法 ######
# 新建文件并覆盖写入
file_path = "D:\\test_data\\test.txt"
f = open(file_path, "w")
f.writelines("hello world!")
f.flush()  # 刷新文件
f.close()  # 关闭文件,自动刷新

# 读取文件并追加
ff = open(file_path, "r+")
print(ff.readable())  # True
print(ff.writable())  # True
txt = ff.read()
print("文件内容:", txt)
# 输入内容
txt = input("请输入内容:")
print("输入内容:", txt)
ff.writelines("\n" + txt)
ff.seek(0)  # 重头读取文件
txt = ff.read()
print("文件内容:", txt, sep="\n")
ff.close()

###### with上下文管理器 ######
file_name = "D:/test_data/file_demo.txt"
with open(file_name, 'w') as write_file_obj:
    '''写入文件'''
    write_file_obj.write("hello\n")
    write_file_obj.write("world\n")

with open(file_name, 'a') as write_file_obj:
    '''追加文件'''
    write_file_obj.write(" ! ")

with open(file_name, encoding='utf-8') as file_obj:
    '''读取文件全部内容'''
    whole_context = file_obj.read()
    print(whole_context.strip())
    print('------------------------')

with open(file_name, encoding='utf-8') as file_obj:
    '''逐行读取文件内容'''
    for line in file_obj:
        print(line.strip())  # 去除左右空格
    print('------------------------')

with open(file_name) as file_obj:
    '''列表形式读取文件内容'''
    lines = file_obj.readlines()
    for line in lines:
        print(line.strip())  # 去除左右空格
    print('------------------------')

file_name = "D:/file_demo_none.txt"
try:
    '''异常处理:文件不存在'''
    with open(file_name) as file_obj:
        whole_context = file_obj.read()
        print(whole_context.strip())
except FileNotFoundError:
    print("File '" + file_name + "' not found!")
else:
    print("File '" + file_name + "' exists!")
finally:
    pass

 

posted @ 2023-02-01 17:44  星瑞  阅读(146)  评论(0编辑  收藏  举报