文件读写
# 读取磁盘里的内容
file=open('a.txt','r')
print(file.readlines()) # 将信息放入列表中
file.close()
# 写入数据
file=open('b.txt','w')
file.write('Python') # 写入数据
file.close()
# 追加数据
file=open('b.txt','a')
file.write('Python') # 追加数据
file.close()
#读与写的二进制文件
src_file=open('logo.png','rb')
target_file=open('copylogo.png','wb')
target_file.write(src_file.read())
target_file.close()
src_file.close()
文件对象常用方法
#python的文件读取
file=open('a.txt','r')
#print(file.read(2)) #读取两行的内容
#print(file.readline()) #获取一行的内容
print(file.readlines()) #获取多行的内容
file.close()
#python的文件写入
file=open('c.txt','a')
#file.write('hello')
lst=['java','go','python']
file.writelines(lst)
file.close()
# python的指针的位置返回数据
file=open('c.txt','r')
file.seek(2) # 根据指针的位置读取数据
print(file.read())
print(file.tell()) # 指针返回的数据
file.close()
# 缓冲区的内容写入
file=open('d.txt','a')
file.write('hello')
file.flush() # 将缓冲去的内容写入文件 但是没有关闭
file.write('world')
file.close()
#with的使用不用手动close(),
with open('a.txt','r') as file:
print(file.read())
#图片的复制
with open('logo.png','rb') as src_file:
with open('copy2logo.png','wb') as target_file:
target_file.write(src_file.read())
#案例
'''
MyContentMgr实现了特殊方法__enter__(),__exit__()称为该类对象遵守了上下文管理器协议
该类对象的实例对象,称为上下文管理器
MyContentMgr()
'''
class MyContentMgr(object):
def __enter__(self):
print('enter方法被调用执行了')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print('exit方法被调用执行了')
def show(self):
print('show方法被调用执行了',1/0)
with MyContentMgr() as file: #相当于file=MyContentMgr()
file.show()
os模块常用的函数
#os模块与操作系统相关的一个模块
import os
#os.system('notepad.exe')
#os.system('calc.exe')
#直接调用可执行文件
os.startfile('C:\\Program Files\\Tencent\QQ\\Bin\\qq.exe')
import os
print(os.getcwd()) # 返回当前的工作目录
lst=os.listdir('../chap15') # 返回指定下的目录与文件
print(lst)
#os.mkdir('newdir2') # 创建目录
#os.makedirs('A/B/C') # 创建多级目录
#os.rmdir('newdir2') #删除目录
#os.removedirs('A/B/C')#删除多级目录
os.chdir('E:\\vippython\\chap15') #将 path设置为当前目录
print(os.getcwd())
# os.path模块的使用
import os.path
print(os.path.abspath('demo13.py')) # 获取目录与文件的绝对路径
print(os.path.exists('demo13.py'),os.path.exists('demo18.py')) #判断文件路径是否存在,存在
为true,不存在 false
print(os.path.join('E:\\Python','demo13.py')) #将目录与目录文件的名称拼接起来
print(os.path.split('E:\\vipython\\chap15\\demo13.py')) #分离文件名与扩展名
print(os.path.splitext('demo13.py')) # 分离文件名与目录名
print(os.path.basename('E:\\vippython\\chap15\\demo13.py')) #从一个目录提取文件名
print(os.path.dirname('E:\\vippython\\chap15\\demo13.py')) #从一个路径获取文件路径,不包括文件名
print(os.path.isdir('E:\\vippython\\chap15\\demo13.py')) # 判断是否为路径
os.path模块常用的方法