Python学习笔记 —— 文件

文件和异常

打开文件

with open('MCR_license.txt') as file_obj:
    contents = file_obj.read()
    print(contents)
  1. 只能打开txt文件,不能打开pdf和office文件
  2. 路径分为相对路径和绝对路径
#相对路径
with open('files\MCR_license.txt') as file_obj:
#绝对路径
with open('E:\SVN\MCR_license.txt') as file_obj:

注意,绝对路径需要注意格式(中文,数字为首字母 都有可能报错)

  1. 逐行读取文件,这个比较重要,数据处理时常用
filename = 'files\MCR_license.txt'
with open(filename) as file_obj:
    """
    读取文件内容
    contents = file_obj.read()
    print(contents)
    """
    
    """
    逐行读取
    for line in file_obj:
        print(line.rstrip())
    """
    
    lines = file_obj.readlines()

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

写入文件

  1. 新建空文件写入
file = 'test.txt'

with open(file,'w') as file_obj:
    file_obj.write('I love programming.')
  1. 替换原有文件
file = 'test.txt'

with open(file,'w') as file_obj:
    file_obj.write('I love programming.\n')
    file_obj.write('I think Python is a good language!\n')
    
with open(file,'w') as file_obj:
    file_obj.write('I love Matlab.\n')
  1. 在原文件后写入
file = 'test.txt'

with open(file,'w') as file_obj:
    file_obj.write('I love programming.\n')
    file_obj.write('I think Python is a good language!\n')
    
with open(file,'a') as file_obj:
    file_obj.write('I love Matlab.\n')

异常处理
类似于Matlab的 try-catch ;Python使用的时 try-except-else

try:
    print(5/0)
except ZeroDivisionError:
    print('Zero Division Error')
else:
    print(20)
    
print(11)

step1:执行try的逻辑
如果,执行正常,再去执行else
否者,执行输出except的逻辑
step2:执行后面的逻辑(第8行)

使用这个的好处是,可以忽略运行过程中产生的失误,继续执行下去
这种处理的方式时防止程序崩溃,尤其在和用户交互的时候很有用

expect 如果执行时,不想执行任何操作,可以直接给pass

exceptpass

存储数据
使用 json 来存储数据,是常用的一种方法
在python中 使用 json ,需要两点

  1. 导入 json 库
import json
  1. 使用两个函数对数据存储和载入
json.dump()    #存储
json.load()    #载入

比如:

import json

numbers = [1,2,3,4,36,8,6,11]

#写入数据
filename = 'number.json'
with open(filename,'w') as file_obj:
    json.dump(numbers,file_obj)
#载入数据
with open(filename) as file_obj:
    num = json.load(file_obj)

print(num)
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值