文件操作

2018-07-26  本文已影响0人  pubalabala

文件操作流程:

打开文件 - 操作文件(读/写) - 关闭文件

  1. 文本文件: open(文件路径,打开方式,编码方式)
    文件路径(必填): 打开哪个文件
    打开方式(默认值是'r'): 决定打开文件后进行什么样的操作
    'r': 读操作(读出来是字符串)
    'rb'/'br': 读操作(读出来是二进制)
    'w': 写操作(将文本数据写入文件中, 如果文件中原本有数据则清空数据)
    'wb'/'bw': 写操作(将二进制数据写入文件中, 如果文件中原本有数据则清空数据)
    'a': 写操作(追加)
    编码方式: 主要针对文本文件的读写(不同的操作系统默认的文本编码方式不同, windows:gbk,mac:utf-8)
  2. 文本文件的读写
    a. 放在工程外面的文件: 使用绝对路径
    b. 工程目录下的文件: (推荐)使用相对路径(相对于工程目录)
    当py文件直接放在工程目录下, 想要使用open打开工程中的其他文件使用'./'开头
    当py文件在工程目录下的子目录中,想要使用open打开工程文件的其他文件使用'../'开头
    c. 打开文件会返回文件句柄
    #读操作 如果文件不存在, 会报错:FileNotFindError
    #(1)打开文件, 返回文件句柄
    file = open('./test1.txt','r',encoding='utf-8')
    #(2)读文件 文件.read():获取文件内容并且返回  参数n: 设置读取内容的长度
    content = file.read()
    #读取完成后指针在读取结束的位置,可以通过seek()函数设置指针的位置
    print(content)
    #(3)关闭文件
    file.close()

    #写操作 如果文件不存在就创建文件
    #打开文件
    file = open('./test1.txt','w',encoding='utf-8')
    string = '我是追加内容'
    #写文件 'w':在写文件的时候会清空原来的数据然后再写入数据 'a':不清空,追加
    file.write(string)
    #关闭文件
    file.close()
  1. 二进制文件的度写操作
    音频, 视频, 图片等文件都是二进制文件
    #打开文件
    file = open('./test/hyd.png','rb')
    #读文件
    image = file.read()
    print(image)
    #关闭文件
    file.close()

    file = open('./test/image.png','wb')
    file.write(image)
    file.close()
  1. 通过with关键字去打开文件
    with open() as 文件变量名:
    文件操作
    在文件操作结束后会自动关闭文件
    with open('./test/文件读写.mp4','rb') as file:
        mp4_data = file.read()

    with open('./test/文件读写(1).mp4','wb') as file:
        file.write(mp4_data)

json文件

json文件, 就是文件后缀是.json的文件. 内容必须是json格式

json格式:

  1. 内容是字符串
  2. 最外层是字典, 字典里面必须键值对
  3. 最外层是数组(列表), 里面的内容必须是数组数据([])
#json是python中内置的一个模块,专门用来处理json数据的
import json

if __name__ == '__main__':
    '''
    json文件的读操作
    '''
    with open('./test.json', 'r', encoding='utf-8') as file:
        '''
        a. 直接用read()去读, 获取到的是字符串数据, 包含了json文件中的所有内容(包括注释部分)
        content = file.read()
        print(content,type(content)
        
        b. load(文件对象): 获取指定json文件中的内容
        dict -> dict
        array -> list
        string -> str
        number -> int/float
        true/flase -> True/False
        null -> None
        '''
        content = json.load(file)
        print(content,'\n',content['grades'][1])

    '''
    json文件的写操作
    
    '''
    with open('./new.json','w',encoding='utf-8') as file:
        #dump(写的内容, 文件对象)
        w_content = 'abc'
        w_content = [
            {'name': 'Jefferson','age':21}
        ]
        json.dump(w_content,file)
    #练习: 输入学生的姓名和电话, 保存到本地(要求下次启动程序, 再添加学生的时候, 之前添加的学生信息还在)
    stu = []
    name = input('姓名:')
    age = input('年龄:')
    tel = input('电话:')
    with open('./stuinfo.json','r',encoding='utf-8') as file:
        stu+=json.load(file)
    with open('./stuinfo.json','a',encoding='utf-8') as file:
        stu.append({'name': name, 'age': age, 'tel': tel})
        json.dump(stu, file)
    print(stu)

    '''
    json模块的其他操作
    loads(字符串,编码方式) -> 将指定的字符串, 转化成json数据
    将字符串转换成字典\将字符串转换成列表
    dumps(对象)
    将json对象转换成json字符串
    字典/列表转换成json字符串
    '''
    content = json.loads('["a",100,false,{"a":1,"abc":"100"}]',encoding='utf-8')
    print(content,type(content))

    content = json.dumps(['aaa',1,True])
    print(content,type(content))
{'name': 'Jefferson', 'age': 21, 'grades': [87.56, 56, 'fd'], 'icon': None} 
 56
姓名:Jefferson
年龄:21
电话:53424
[{'name': 'Jefferson', 'age': '21', 'tel': '130'}, {'name': 'Jack', 'age': '32', 'tel': '4432'}, {'name': 'Jefferson', 'age': '21', 'tel': '53424'}]
['a', 100, False, {'a': 1, 'abc': '100'}] <class 'list'>
["aaa", 1, true] <class 'str'>

异常捕获

格式:

try:
    需要捕获异常的代码
except:
    出现异常会执行的代码

try:
    需要捕获异常的代码
except:错误类型
    出现指定异常才会执行的代码

练习

utls.py

"""__author__ == Jefferson"""

import json

def read_file(path):
    try:
        if path.endswith('.json'):
            with open(path,'r',encoding='utf-8') as file:
                result = json.load(file)

        else:
            with open(path,'r',encoding='utf-8') as file:
                result = file.read()
        return result
    except FileNotFoundError:
        print('文件读取错误!')
        return None

def write_file(content,path):
    try:
        if path.endswith('.json'):
            with open(path,'w',encoding='utf-8') as file:
                temp = json.loads(content)
                json.dump(temp,file)
        else:
            with open(path,'w',encoding='utf-8') as file:
                file.write(content)
        print('已成功写入到'+path)
    except FileNotFoundError:
        print('文件写入错误!')
        return None

if __name__ == '__main__':
    pass

homework.py

"""__author__ == Jefferson"""
import utls


if __name__ == '__main__':
    content = input('请输入要写入文件的内容:')
    path = input('请输入要写入的文件路径:')
    utls.write_file(content,path)
    print('读取内容:',utls.read_file(path))

运行结果:

请输入要写入文件的内容:{"name":"魏盼","age":21}
请输入要写入的文件路径:./test.json
已成功写入到./test.json
读取内容: {'name': '魏盼', 'age': 21}
上一篇下一篇

猜你喜欢

热点阅读