Python 语法一 2021-11-03

注:来源莫烦PYTHON

1、数据

1.1 List 列表 [ ]
files = [“f1.txt”, “f2.txt”, “f3.txt”, “f4.txt”, “f5.txt”]

1.2 Dict 字典 { }
字典中的 key 都是唯一的, 而 value 是多样的
files = {“ID”: 111, “passport”: “my passport”, “books”: [1,2,3]}

1.3 Tuple 元组 ( )
它里面的东西不可变,定下来就定下来了,不让你变
files = (“file1”, “file2”, “file3”)

1.4 Set 合集 ( [ ] )
set 里面只会存在非重复的元素,不管你往里面加了多少相同元素,这些相同元素都会坍缩成一个,可以运用它来做交集并集等操作,集合中的元素,其实是没有顺序的。
my_files = set([“file1”, “file2”, “file3”])
my_files.add(“file4”)
my_files.remove(“file3”)
print("交集 ", your_files.intersection(my_files))
print("并集 ", your_files.union(my_files))
print("补集 ", your_files.difference(my_files))

2、函数

def f(x, a=1, b=1, c=0):
    return a*x**2 + b*x + c*1

2.1 全局和局部变量
全局 global : 函数里外都能用 (公用)
局部 local : 仅在函数内有用 (私有)

3、类

class File:
    def __init__(self, name, create_time="today"):
        self.name = name
        self.create_time = create_time

my_file = File("my_file")
print(my_file.name)

self 是作为类自己的一个索引,不管你在定义类的时候,想要获取这个类的什么属性或功能,都可以通过 self 来获取
__init__ 是类的一个功能,在__init__() 里加上传入参数。并且在初始化 File() 的时候传入你要 __init__ 的参数。

继承

class File:
    def __init__(self, name, create_time="today"):
        self.name = name
        self.create_time = create_time
    
    def get_info(self):
        return self.name + "is created at" + self.create_time

class Video(File):  # 继承了 File 的属性和功能
    def __init__(self, name, window_size=(1080, 720)):
        # 将共用属性的设置导入 File 父类
        super().__init__(name=name, create_time="today") 
        self.window_size = window_size

class Text(File): # 继承了 File 的属性和功能
    def __init__(self, name, language="zh-cn"):
        # 将共用属性的设置导入 File 父类
        super().__init__(name=name, create_time="today") 
        self.language = language
    
    # 也可以在子类里复用父类功能
    def get_more_info(self):
        return self.get_info() + ", using language of " + self.language

v = Video("my_video")
t = Text("my_text")
print(v.get_info())     # 调用父类的功能
print(t.create_time)    # 调用父类的属性
print(t.language)       # 调用自己的属性
print(t.get_more_info()) # 调用自己加工父类的功能

私有属性和功能
_ 一个下划线开头
弱隐藏 不想让别人用 (别人在必要情况下还是可以用的)
__ 两个下划线开头
强隐藏 不让别人用

class File:
    def __init__(self):
        self.name = "f1"
        self.__deleted = False  # 我不让别人用这个变量
        self._type = "txt"      # 我不想别人使用这个变量

4、Module 模块

module主要是为了一个相对比较大的工程,涉及到多个文件之间的互相调用关系。

5、文件

5.1 创建文件

f = open("new_file.txt", "w")   # 创建并打开
f.write("some text...")         # 在文件里写东西
f.close()                       # 关闭

5.2 读文件
在文件中每行记录列表当中的一个值,可以用 writelines(),那么在读文件的时候, 也可以 readlines() 直接读出来一个列表
readline() 一行一行读取,取代一次性读取,不让内存被一次性占满

5.3 文件编码,中文乱码
两种方式

with open("chinese.txt", "wb") as f:
    f.write("这是中文的,this is Chinese".encode("gbk"))

with open("chinese.txt", "rb", ) as f:
    print(f.read())
    print(f.read().decode('gbk'))  # windows在本机尝试,可以试试这个
with open("chinese.txt", "r", encoding="gbk") as f:
    print(f.read())

在这里插入图片描述

with open("new_file.txt", "r") as f:
    print(f.read())
with open("new_file.txt", "r+") as f:
    f.write("text has been replaced")
    f.seek(0)       # 将开始读的位置从写入的最后位置调到开头
    print(f.read())

6、文件目录

6.1 文件目录操作

import os 

print("当前目录:", os.getcwd())
print("当前目录里有什么:", os.listdir())

6.2 文件管理系统

if os.path.exists("user/mofan"):
    print("user exist")
else:
    os.makedirs("user/mofan") #创建一个文件夹
    print("user created")
print(os.listdir("user"))


if os.path.exists("user/mofan"):
    os.removedirs("user/mofan")#删除一个文件夹
    print("user removed")
else:
    print("user not exist")

6.3 文件目录多种检验
有没有某个文件
否是一个文件
否是一个文件夹

import os
os.makedirs("user/mofan", exist_ok=True)
with open("user/mofan/a.txt", "w") as f:
    f.write("nothing")
print(os.path.isfile("user/mofan/a.txt")) # True
print(os.path.exists("user/mofan/a.txt")) # True
print(os.path.isdir("user/mofan/a.txt")) # False
print(os.path.isdir("user/mofan"))  # True

6.4 创建副本

import os
def copy(path):
    filename = os.path.basename(path)   # 文件名
    dir_name = os.path.dirname(path)    # 文件夹名
    new_filename = "new_" + filename    # 新文件名
    return os.path.join(dir_name, new_filename) # 目录重组
print(copy("user/mofan/a.txt"))
def copy(path):
    dir_name, filename = os.path.split(path)
    new_filename = "new_" + filename    # 新文件名
    return os.path.join(dir_name, new_filename) # 目录重组
print(copy("user/mofan/a.txt"))

7、正则表达式

正则表达式 regex 就是为了让你尽情匹配文字,用一些规则或者模板来帮你找到文字,替换文字的工具。
批量修改很多文件中出现某种固定模式的文字时

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值