caxa发生文件读写异常_文件和异常

最近在学习python之前网上搜了很多的视频,发现很多概念之类的讲的不是很清楚,就找到了这本最经典的教材,跟着打一遍代码,今天看了文件和异常,笔记整理如下:

导入文件

Python打开所需的外在文件:

file_path=r'D:\pythondata\test\text_files\2.txt'

with open(file_path) as file_object:

contents2=file_object.read()

print(contents2)

print(contents2.rstrip()) rstrip函数用于去掉文件末尾的空格

file_path=r'D:\pythondata\test\text_files\1.txt'

with open (file_path) as file_object:

for line in file_object:

print(line.rstrip())

读取文件的内容,每一行以列表形式储存:

file_path=r'D:\pythondata\test\text_files\1.txt'

with open (file_path) as file_object:

lines=file_object.readlines()

"""readlines()从文件中读取每一行,并储存在一个列表中"""

for line in lines:

print(line.rstrip())

readlines()函数从文件中读取每一行,并储存在一个列表中。

rstrip函数仅可删除末尾的换行符:

Strip()函数可以删除读取文件时所遇到的空格,打印连续的字符。

往打开文件里写入内容,即在open中加入一个实参:

filename=r'D:\pythondata\未建测试.txt'

with open(filename,'w') as file_object:

file_object.write('you love python!')

通常来说,‘w’的位置,若不写,文件以只读模式打开,通常:

读取模式(‘r’)

写入模式(‘w’)

附加模式(‘a’)

读写模式(‘r+’)

第一行路径,分两种情况,若所指定路径文件不存在,则会在你写入后,在所指定路径下新建‘未建测试.txt’这个文件;若所指定路径原先已经存在“未建测试.txt“这个文件,python则会在你写入前,将文件中的内容清空,写入‘you love python!‘。(这点要慎重)

Ps:只能将字符串写入,若写数值型,则应先str()。

多行写入:末尾加上\n用于换行。

filename=r'D:\pythondata\读写测试.txt'

with open(filename,'w') as file_object:

file_object.write('do you love me?\n')

file_object.write('ok, you love him!\n')

附加模式:不会覆盖原有内容,将你写的附加到文件末尾,如你所指定的文件不存在,则会帮你新建。

filename=r'D:\pythondata\programming.txt'

with open(filename,'a') as file_object:

file_object.write('我的头可不是面团捏的\n')

file_object.write('老铁,666\n')

filename=r'D:\pythondata\programming.txt'

with open(filename,'a') as file_object:

file_object.write('最近还好吗\n')

file_object.write('哦,是的,特尔瓦基先生\n')

上述代码执行,则在programming.txt中出现四行文字。

Try-excep-else模块处理异常

1.除零异常(ZeroDivisionError):

try:

print(5/0)

except ZeroDivisionError:

print("you can't divide by zero!")

编写一个除法计算器:

print("give me two numbers,and i'll divide them.")

print("enter 'q' to quit.")

while True:

first_number = input("\nfirst number: ")

if first_number=='q':

break

second_number=input("second number: ")

if second_number=='q':

break

try:

answer=int(first_number)/int(second_number)

except ZeroDivisionError:

print("you can't divide by 0")

else:

print(answer)

2.FileNotFoundError异常(找不到文件发生异常):

文件下没有天呐努这个文件,打开时报FileNotFoundError错误:

filename=r'D:\pythondata\天呐努.txt'

with open(filename) as file_object:

contents=file_object.read()

print(contents)

处理异常:

filename=r'D:\pythondata\天纳努.txt'

try:

with open(filename) as file_object:

contents=file_object.read()

print(contents)

except FileNotFoundError:

msg="sorry,the file"+filename +"dees not exist."

print(msg)

split()函数将字符串切割成单词列表:

用split函数将alice这个文本单词切割,然后看看有多少个单词:

filename=r'D:\pythondata\alice.txt'

try:

with open(filename) as f_obj:

contents=f_obj.read()

except FileNotFoundError:

print("sorry,the file"+filename+"doesn't exist.")

else:

#计算文件大致包含多少单词

words=contents.split()

num_words=len(words)

print("the file "+filename+" has about "+str(num_words)+" words")

多文本计算单词数:

以上,except也可以跟pass占位。

存储数据(json)

Json.dump()函数

import json “导入json模块“

numbers=[2,3,5,7,11,13] 创建数字列表

filename='number.json' 给定一个文件名,赋给变量filename

with open(filename,'w') as f_obj: 以写入模式打开这个文件

json.dump(numbers,f_obj) 用json.dump函数把numbers里的值写入文件

运行后没有结果,你会在文件目录下看到多了一个number.json这个文件,打开后即列表。

Json,load()函数(加载数据)

import json

filename=r'D:\pythondata\test\number.json'

with open(filename) as f_obj:

numbers=json.load(f_obj)

print(numbers)

新老用户问候-函数调用&json.load()&json.dump()

5

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值