一、怎么导入自己的模块
from 模块 import 函数
import 模块.函数
"""测试代码"""#主程序的执行入口 只有当你在当前模块下面执行的时候 才会执行
if __name__ == '__main__':"""断言"""
二、文件处理
#1、
#a、首先在同级目录下新建一个txt文件,里面可添加文字方便之后查看结果
#b、再新建一个py文件
#r+ w+ a+
#read write append
#rb rb+ wb wb+ ab ab+ 做单元测试的时候
file=open("1.txt","r+")
res=file.read()#进行完一次读取操作后 光标就到文本
file.write("777")
print(res)
#关闭文件
file.close()#2、推荐
#a、file文件open之后默认是r 只读模式 如果你要写入的内容 报错:io.UnsupportedOperation: not writable
#b、r+ 可读可写 先写的话 从头开始覆盖写 读光标之后的内容 读写跟踪光标走
#c、如果要写入中文 要注意编码格式 encoding="gbk" encoding="utf-8"file=open("1.txt","r+",encoding="gbk")
res=file.read()#进行完一次读取操作后 光标就到文本
file.write("卡卡西")
print(res)
file.close()#3、decode encode 编码关系#4、慎用覆盖 不推荐
#a、w 只写 硬读,会报错:io.UnsupportedOperation: not readable
#b、w+ 可读可写 不管是w 还是w+ 如果文件存在 就直接清空 再重写 反之则新建一个文件 然后写file=open("1.txt","w+",encoding="utf-8")
file.write("1234")
print(res)
file.close()#5、a 追加 a+ 推荐
#a.如果文件存在 就直接追加写 写在后面 如果不存在 则新建一个文件进行结果写入
file=open("1.txt","a",encoding="utf-8")
#换行追加
file.write("\n4321")
print(res)
file.close()#拓展:怎么移动光标#print(file.read()) 读取所有内容
#print(file.readline()) 按行读取
#print(file.readlines()) 读取多行 返回的是列表#1._writeline("内容")
#1._writelines("内容")
三、创建文件夹
import os
#新建一个目录 新建一个文件夹
#os.mkdir("3")#跨级新建目录 用/ 符号来代表路径的不同层级 必须确保上面的层级是存在的
os.mkdir("3/123") #相对路径os.mkdir("D:\\test_4") #绝对路径
#转义字符 \n \r 我们可以通过加\ 还有r R 来让转义字符失效#删除 删除文件也是一级一级删除的 不推荐
os.rmdir("3")
#OSError: [WinError 145] 目录不是空的。: '3'#拓展1:怎么新建文件open 删除文件#路径获取1: 获取当前工作目录 具体到最后一级目录
path1=os.getcwd()
print("获取到的当前路径是:{0}".format(path1))
#获取到的当前路径是:D:\PycharmProjects\class_01#路径获取2: 获取当前文件所在的绝对路径 具体到 模块名
path2=os.path.realpath(__file__)
print("获取到的当前路径是:{0}".format(path2))
#获取到的当前路径是:D:\PycharmProjects\class_01\123.py#拓展2:如何拼接路径
path3=os.getcwd()+"\\4"
print(path3)
os.mkdir(path3)#join 必须确保上面的层级是存在的
path4=os.path.join(os.getcwd(),"4","6")
print(path4)
os.mkdir(path4)path5=os.path.join(os.getcwd(),"4\\text")
print(path5)
os.mkdir(path5)#判断是文件还是目录
print(os.path.isfile(os.getcwd())) #返回值 布尔值
print(os.path.isdir(os.getcwd())) #返回值 布尔值 dir directory#怎么去判断文件是否存在
os.path.exists("D:\PycharmProjects\class_01\123.py")#罗列出当前路径的所有文件和目录
print(os.listdir(os.getcwd()))