一、模块&包

#pack为一个包(一个文件夹),first为其中的一个.py文件
#导入包内模块
import pack.first
#导入包内模块并设置别名
import pack.first as one
#from导入包名,import导入模块
from pack import first
#from包名.模块名 import 功能代码,需保证当前模块没有导入模块的功能代码
from pack.first import show
#from 包名 import * ,默认不会导入包内所有模块,需要在init文件使用__all__=["first","second"]
from pack import *
#从当前包导入对应模块
from . import first
  • 不同路径的py如何导入
import sys
sys.path.append("D/")
import other_moudle
  • if __name__ = "__main__"
#导入模块时有初始化代码会输出数据,要想不执行初始化数据,判断是否为当前模块,若在当前模块,__name__永远为__main__
#是当前模块才执行if下的语句
if __name__ = "__main__"
	print("初始化other_moudle模块")

二、文件基础操作

r:只读
w:只写
a:追加
rb:以二进制方式读取
wb:以二进制方式写入
ab:以二进制方式追加
+的方式最好不用:r+,w+

  • 绝对路径文件,写入
file=open("D:/chy/test.txt","w",encoding="utf-8")
#w模式会覆盖原来文件内的内容
file.write("bbb")
file.close()
  • 追加模式写入
#a,追加模式
file=open("D:/chy/test.txt","a",encoding="utf-8")
file.write("hahah")
file.close()

python 导入模块重名 python导入模块命令_python 导入模块重名

  • 二进制方式读取,不需要写编码格式,会自动编码
    编码:将str转换为二进制
    解码:将二进制转换为str
#以二进制方式读取,二进制不需要指定编码格式,如果指定会报错ValueError: binary mode doesn't take an encoding argument
# file=open("D:/chy/test.txt","rb",encoding="utf-8")
# file.read()
# file.close()

file=open("D:/chy/test.txt","rb")
content=file.read()
print(content)
file.close()

python 导入模块重名 python导入模块命令_初始化_02

file=open("D:/chy/test.txt","rb")
content=file.read()
#将二进制文件解码
content=content.decode("utf-8")
print(content)
file.close()

python 导入模块重名 python导入模块命令_python 导入模块重名_03

  • 二进制方式写入,需要先编码
file=open("D:/chy/test.txt","wb")
content="hahaha"
#需要将二进制编码转换为str
file_content=content.encode("utf-8")
file.write(file_content)
file.close()
  • r+,支持读写,有局限性,存取小批量数据

总结:不是二进制方式时,open一定加encoding=“utf-8”

  • 简略写法:使用with,包含close
with open("D:/chy/{}.jpg".format(num),"wb") as f:
    f.write(response.content)