python文件和异常

#encoding:utf-8

#读取文件
'''关键字with在不再需要访问文件时将其关闭'''
with open('pi_digits.txt') as file_object:
    contents = file_object.read()   #read()把文件的全部内容读取成一个长长的字符串
    print(contents.rstrip())    #rstrip()的作用是删除字符串末尾的空白

#绝对文件路径读取文件
print("\n")
file_path = '/home/shihao/Desktop/python_work/pi_digits.txt'
with open(file_path) as file_object:
    contents = file_object.read()
    print(contents.rstrip())

#逐行读取文件内容
print("\n")
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
    for line in file_object:
        print(line.rstrip())

#创建一个包含文件各行内容的列表
print("\n")
file_name = 'pi_digits.txt'
with open(file_name) as file_object:
    lines = file_object.readlines()  #readlines()从文件中读取每一行,并将其存放在一个列表中

for line in lines:
    print(line.rstrip())

#写入文件
file_name = 'programming.txt'
with open(file_name, 'w') as file_object:
    file_object.write("I love proggramming.\n")       #write()将一个字符串写入文件
    file_object.write("I am shihao\n")

#附加到文件
file_name = 'programming.txt'
with open(file_name, 'a') as file_object:
    file_object.write("I love you!")
#encoding:utf-8

#处理ZeroDivisionError
try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

#处理FileNotFoundError
try:
    file_name = 'alice.txt'
    with open(file_name) as file_object:
        contents = file_object.read()
except FileNotFoundError:
    print("The file " + file_name + " not found")
#encoding:utf-8

#使用json.dump()来存储数据列表
import json
numbers = [2, 3, 5, 7, 11, 13]
file_name = 'numbers.json'
with open(file_name, 'w') as f_obj:
    json.dump(numbers, f_obj)

#使用json.load()读取列表到内存中
with open(file_name) as f_obj:
    numbers = json.load(f_obj)
print(numbers)
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值