Python-day-09

2018-07-27  本文已影响0人  sawyerwh

一、模块管理函数和类

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

print('====')
import other
# 在模块中声明全局变量都可以使用(普通变量、函数、类)
print(other.func_other(), other.name, other.abc)
print('====')

from other2 import func2
func2()


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

print(__name__)
import 模块名 as 新的名字
from 模块名 import 函数名 as 新的函数名
"""
import math as my_math
print(my_math.pi)

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


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

# 练习:使用一个模块,用来管理所有和形状相关的功能
# (求两个点之间的距离、求圆的周长、求圆的面积、求矩形的周长和面积等)

二、基本文件操作

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

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


if __name__ == '__main__':
    # 2.文本文件读操作
    """
    a.放在工程外面的文件,写绝对路径:/Users/yuting/Desktop/test.txt
    """
    # open('/Users/yuting/Desktop/test.txt')
    (推荐)
    b.将文件放到工程目录下的某个位置,写相对路径(相对于工程目录):./相对路径 或者 ../相对路径
    当py文件直接放在工程目录下,想要使用open打开工程中的其他文件使用'./'
    当py文件在工程目录的子目录下面,想要使用open打开工程中的其他文件使用'../'
    """
    # open('./test1.txt')
    # open('./files/test2.txt')
    # open('./files/text/test2.txt')
    # 1.打开文件
    # 打开文件,返回文件句柄(文件代言人)
    f = open('./test1.txt', 'r', encoding='utf-8')

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

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

3.文本文件的写操作

    # 1.打开文件
    """
    注意: 以读的方式打开文件,如果这个文件不存在,会报错FileNotFindError;
         以写的方式打开文件,如果这个文件不存在,就会创建这个文件
    """
    f = open('./test11.txt', 'a', encoding='utf-8')
    # 2.写操作
    """
    'w':在写的时候会清空文件中原来的内容,然后再往里面写数据
    'a':在原文件内容的最后添加新的数据
    """
    f.write('疑是地上霜')
    # 3.关闭文件
    f.close()

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

    音频、视频、图片文件,都是二进制文件
    """
    f = open('./files/luffy.jpeg', 'rb')
    # 读文件
    image_data = f.read()
    # bytes: python中二进制数据对应的数据类型
    print(type(image_data),image_data)
    # 关闭文件
    f.close()

    """二进制文件的写操作"""
    f = open('./files/new.jpeg', 'wb')
    f.write(image_data)
    f.close()

5.通过with关键字去打开文件

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

"""
# 读
with open('./files/一人之下.mp4','rb') as file:
    mp4_data = file.read()

# 写
with open('./new.mp4', 'wb') as f:
    f.write(mp4_data)

三、json文件

# json是python中内置的一个模块,专门用来处理json数据的
import json

if __name__ == '__main__':

1.json文件的读操作

    # 打开json文件
    with open('./files/test.json', 'r', encoding='utf-8') as f:
        # 直接使用read()去读,获取到的是字符串数据,包含了json文件中的所有的内容(包括注释部分)
        # conten = f.read()
        # print(conten, type(conten))
        """
        load(文件对象): 获取指定json文件中的内容,返回值的类型是json文件最外层的对应的数据类型
        dict ---> dict
        array ---> list
        string ---> str
        number ---> int/float
        true/flase --> True/Flase
        null ---> None
        """
        content = json.load(f)
        print(content, type(content), content['成绩'][1])

2.json文件的写操作

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


####3.json模块的其他操作
    # {"a": true, "b": 2}
    #
    content = json.loads('["a",100, false,{"a":1, "abc":"100"}]', encoding='utf-8')
    print(content, type(content))

    """
    dumps(对象)
    将对象转换成json字符串
    字典/列表转换成json字符串
    """
    content = json.dumps(['aaa', 1, True])
    # content = '["aaa", 1, true]'
    content2 = str(['aaa',1, True])
    # content2 = '['aaa', 1, True]'
    print(content,content2, type(content))

四、异常捕获

try:
    需要捕获异常的代码
except:
    出现异常会执行的代码
    
try:
    需要捕获异常的代码
except 错误类型:
    捕获到指定的错误类型,才执行的代码
if __name__ == '__main__':
    try:
        with open('./aaaa.txt') as ff:
            print('打开成功')
    except FileNotFoundError:
        print('===')
        open('./aaa.txt','w')

上一篇 下一篇

猜你喜欢

热点阅读