dump文件_文件和异常

67d9e2791c40722b196686377fa2917b.png

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

导入文件

Python打开所需的外在文件:

file_path=r'D:pythondatatesttext_files2.txt'
with open(file_path) as file_object:
contents2=file_object.read()
print(contents2)

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

file_path=r'D:pythondatatesttext_files1.txt'
with open (file_path) as file_object:
    for line in file_object:
        print(line.rstrip())

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

file_path=r'D:pythondatatesttext_files1.txt'
with open (file_path) as file_object:
    lines=file_object.readlines()
    """readlines()从文件中读取每一行,并储存在一个列表中"""

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

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

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

09163f242e5f16dc265b03dd23188457.png

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

7e5b49442d2b1e047972bd76b3b13d50.png

往打开文件里写入内容,即在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:pythondataprogramming.txt'
with open(filename,'a') as file_object:
    file_object.write('我的头可不是面团捏的n')
    file_object.write('老铁,666n')

filename=r'D:pythondataprogramming.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()函数将字符串切割成单词列表

5eed18ab6c8f3ced5abfe5598efc2064.png

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

filename=r'D:pythondataalice.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")

多文本计算单词数:

b920b6197b86d54882ab04a407e09509.png

以上,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:pythondatatestnumber.json'
with open(filename) as f_obj:
    numbers=json.load(f_obj)
print(numbers)

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

cf68dccfa1e408115ff84b181f3ed2b3.png

5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值