美文网首页
day_09 模块管理、文件操作、json文件、异常捕获

day_09 模块管理、文件操作、json文件、异常捕获

作者: 我是一只菜鳥 | 来源:发表于2018-07-26 19:27 被阅读0次

1.模块管理

1.什么是模块
一个.py文件就是一个模块
2.import
可以通过import关键字导入其它的模块

import 模块名(.py文件名)
直接导入模块的时候,相当于把被导入模块里的内容粘贴到import的位置
3.怎么使用模块中的内容?什么内容是可以使用的?
import 模块名 --->导入模块中的所有内容
模块名.变量名(函数名、类):的方法去使用模块中的内容

在模块中声明全局变量都可以使用(普通变量、函数、类)

other.py

name = 10
print(name)

def func_other():
    global abc
    abc = 100
    print('====')

# 打印当前模块的名字
print(__name__)

管理模块.py

import other

# 在模块中声明全局变量都可以使用
print(other.func_other(), other.name, other.abc)

>>>
10
other
====
None 10 100
  1. from 模块 import 内容列表1,内容2... --->导入模块中的指定内容
    使用内容的时候,不用在被导入的变量或函数或类前面加模块名

other2.py

def func_other2():
    print('~~~~')
    return 100

# 在这写当前模块中写不需要被其它模块导入和粘贴的代码
if __name__=='__main__':
    name = 1010
    print(name)

管理模块.py

from other2 import func_other2
print(func_other2())

import other2

>>>
~~~~
100

5.阻止被导入的模块中的不必要的代码被粘贴到当前模块
一般情况下,除了函数的声明和类的声明以外,其它的代码都放在if里面

name:是每个模块自带的一个属性,是用来保存当前这个模块的名字的。
但是当正在执行当前模块的时候,这个模块是固定的'main'

print('==:', other.__name__)
print(__name__)

if __name__=='__main__':
    pass  # 这个里面的代码不会被其它模块使用

>>>
==: other
__main__

6.使用as重命名
import 模块名 as 新的名字
from 模块名 import 函数名 as 新的函数名

import math as my_math
print(my_math.pi)

from random import randint as my_randint
print(my_randint(1, 10))

>>>
3.141592653589793
8

2.基本文件操作

(所有)文件操作流程:打开文件 -> 操作文件(读/写) -> 关闭文件

2.1.打开文件:open(文件路径, 打开的方式, 编码方式)

文件路径(必填) --> 决定打开那个文件

打开方式(默认值是'r') --> 决定打开文件后是进行什么操作
  ''r' - 读操作(读出来是字符串)
   'rb'/'br' - 读操作(读出来的数据是二进制)
   'w' - 写操作(可以将文本数据写入文件中)
   'wb'/'bw' - 写操作(可以将二进制数据写入文件中)
   'a' - 写操作(追加)

编码方式 --> 主要针对文本文件的读写(不同的操作系统默认的文本编码方式不同,
Windows -> gbk, mac -> utf_8)

2.2.文本文件读

a.放在工程外面的文件:写绝对路径:D:/course/test.txt

open('D:/course/test.txt')

b.将文件放到工程目录下的某个位置,写相对路径(相对于工程目录):./相对路径 或者 ../相对路径
当py文件直接放在工程目录下,想要使用open打开工程中的其他文件使用'./'
当py文件在工程目录的子目录下面,想要使用open打开工程中的其他文件使用'../'

open('./test2.txt')
open('./files/test3.txt')

文件操作流程

1.打开文件

 # 打开文件,返回文件句柄(文件)
    f = open('./test2.txt', 'r', encoding='utf-8')

2.读文件(获取文件的文件内容)

    """
    文件.read(): 获取文件内容,并且返回
    read(n) --> 设置读的长度
    """
    content = f.read()
    print(content)

3.关闭文件

f.close()

2.3.文本文件的写操作

# 1.打开文件
    """
    注意:以读的方式打开文件,如果这个文件不存在,回报错fileNotFindError:
          以写的方式打开文件,如果这个文件不存在,就好创建这个文件
    """
    f = open('./test2.txt', 'w', encoding='utf-8')
    """
    'w':在写的时候回清空文件中原路的内容,然后再往里面写数据
    'a':在源文件内容的最后添加新的数据
    """
    # 2.写操作
    f.write('束带结发')
    # 3.关闭文件
    f.close()

2.4.二进制文件的读写操作

音频、视频、图片文件,都是二进制文件

读文件

f = open('./files/lufei.jpg', 'rb')
    # 读文件
    image_data = f.read()
    # bytes:python中二进制数据对应的数据类型
    print(type(image_data), image_data)
    # 关闭文件
    f.close()

写文件

f = open('./files/new.jpg', 'wb')
    f.write(image_data)
    f.close()

2.5.通过with关键字取打开文件

with open() as 文件变量名:
      文件操作
在文件操作结束后会自动去关闭文件

# 读
    with open('./files/new.jpg', 'rb') as f:
        jpg_data = f.read()

    #写
    with open('./files/new.jpg', 'wb') as f:
        f.write(jpg_data)

3.json文件

json文件(文本),就是文件后缀是.json的文件。内容必须是json格式的内容
json格式:
1.内容是字符串
2.最外层是字典,字典里面就必须是键值对
3.最外层是数组(列表),数组里面的内容必须是数组数组

3.1.json文件的读操作

    with open('./files/test.json', 'r', encoding='utf-8') as f:
        # 直接使用read()去读,获取到的是字符串数据,包含了json文件中的所有内容(包括注释部分)
        # content = f.read()
        # print(content, type(content))

        """
        load(文件对象):获取指定json文件中的内容,返回值的类型是json文件最外层的对应的数据类型
        dict --> dict
        array --> list
        string --> str
        number --> int/float
        true/flase --> True/Flase
        null --> None
        """
        # json
        # // 最外层只能是一个字典,一个数组,一个字符串
        # // 支持的数据类型:字符串("abc"), 数字(1, 2.222, ), 布尔值(true / false), 数组([1, 23, "ads"]), 字典({key: value})
        # // null(None)空

        content = json.load(f)
        print(content, type(content))

3.2json文件的写操作

    with open('./files/new.json', 'w', encoding='utf-8') as f:
        # 写数据
        """
        dump(写的内容,文件对象)
        """
        w_content = [
            {'name': 'a1', 'age': 18},
            {'name': 'a2', 'age': 20}
        ]
        json.dump(w_content, f)

练习:输入学生的姓名和电话,保存到本地(要求下次启动程序,添加学生时,之前添加的学生信息还在)

name = input('名字:')
    tel = input('电话:')
    student = {'name': name, 'tel':tel}

    try:
        with open('./files/students.json', 'r', encoding='utf-8') as f:
            all_students = json.load(f)

    except FileNotFoundError:
        all_students = []

    all_students.append(student)
    with open('./files/students.json', 'w', encoding='utf-8') as f:
        json.dump(all_students, f)

3.3.json模块的其他操作

loads(字符串, 编码方式) --> 将指定的字符串(json字符串),转化成json数据
将字符串转换成字符串\将字符串转换成列表

 content = json.loads('{"a":true, "b":2}', encoding='utf-8')
 print(content, type(content))


>>>
{'a': True, 'b': 2} <class 'dict'>

dumps(对象)
将对象转换成json字符串
字典\列表转换成json字符串

content = json.dumps(['aaa', 1, True])
# content = '["aaa", 1, true]'
content2 = str(['aaa', 1, True])
# content2 = '['aaa', 1, True]'
print(content, type(content))


>>>
["aaa", 1, true] ['aaa', 1, True] <class 'str'>

4.异常捕获

出现异常(错误)不想让程序崩溃,就可以进行异常捕获
try:
需要捕获异常的代码
except:
出现异常会执行的代码

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

if __name__ == '__main__':
    try:
        with open('./aaa.txt') as f:
            print('打开成功')
    except FileNotFoundError:
        print('===')
        with open('./aaa.txt', 'w') as f:
            pass

相关文章

网友评论

      本文标题:day_09 模块管理、文件操作、json文件、异常捕获

      本文链接:https://www.haomeiwen.com/subject/ykcbmftx.html