编码格式
码格式默认是UTF-8,如果要更改,使用encoding=gbk
文件的读写操作
内置函数**open()**创建文件对象
file = open(filename[,mode(打开模式默认为只读),encoding(默认文本文件中字符的编写格式为gbk)])
例:
file=open('a.txt','r',encoding='UTF-8')
print(file.readlines())
file.close()
运行结果:
文件的类型(按文件中数据的组织形式分):
- 文本文件:存储的是普通“字符文本”,默认为unicode字符集,可以使用记事本程序打开
- 二进制文件:把数据内容用“字节”进行存储,无法用记事本打开,必须使用专用的软件打开,举例:mp3音频文件、jpg图片、doc文档等
常用的文件打开模式
r:以只读模式打开文件
文件的指针将会放在文件的开头
例:
file=open('a.txt','r',encoding='UTF-8')
print(file.readlines())
file.close()
运行结果:
w:以只写模式打开文件
如果文件不存在则创建,如果文件存在,则覆盖原有内容,文件指针在文件的开头
例:
原b.txt文件内容:
file=open('b.txt','w',encoding='UTF-8')
file.write('hello')
file.close()
执行写操作后b.txt内容:
a:以追加模式打开文件
如果文件不存在则创建,文件指针在文件开头,如果文件存在,则在文件末尾追加内容,文件指针在原文件末尾
file=open('b.txt','a',encoding='UTF-8') #执行多少次,就会追加多少次
file.write('GOOD')
file.close()
执行追加操作后b.txt内容:
b:以二进制方式打开文件
不能单独使用,需要与其他模式一起使用,rb或者wb
例:复制图片
src_file=open('logo.png','rb')
target_file=open('copylogo','wb')
target_file.write(src_file.read()) #边读边写
target_file.close()
src_file.close()
+:以读写方式打开文件
不能单独使用,需要与其他模式一起使用,a+
文件对象的常用方法
read([size]):从文件中读取size个字节或字符的内容返回。若省略[size],则读取到文件末尾,即一次读取文件所有内容
file1=open('a.txt','r',encoding='UTF-8')
print(file1.read())
file1.close()
运行结果:
file1=open('a.txt','r',encoding='UTF-8')
print(file1.read(2))
file1.close()
运行结果:
readline():从文本文件中读取一行内容
file1=open('a.txt','r',encoding='UTF-8')
print(file1.readline())
file1.close()
运行结果:
readlines():把文本文件中每一行都作为独立的字符串对象,并将这些对象放入列表返回
file1=open('a.txt','r',encoding='UTF-8')
print(file1.readlines())
file1.close()
运行结果:
write(str):将字符串str内容写入文件
原c.txt文件内容:
file2=open('c.txt','a',encoding='UTF-8')
file2.write('hello')
file2.close()
运行代码后c.txt文件内容:
writelines(s_list):将字符串列表s_list写入文本文件,不添加换行符
file2=open('c.txt','a',encoding='UTF-8')
lst=['java','go','python']
file2.writelines(lst)
file2.close()
运行代码后c.txt文件内容:
seek(offset[,whence]):把文件指针移动到新的位置,offset表示相对于whence的位置。
offset为正往结束方向移动,为负往开始方向移动
whence为0从文件头开始计算(默认值),为1从当前位置开始计算,为2从文件尾开始计算
file3=open('c.txt','r',encoding='UTF-8')
file3.seek(2)
print(file3.read())
print(file3.tell()) #获取当前文件指针的位置
file3.close()
运行结果:
tell():返回文件指针的当前位置
flush():把缓冲区的内容写入文件,但不关闭文件
原d.txt文件内容:
#先flush后close
file4=open('d.text','a')
file4.write('hello')
file4.flush()
file4.write('world')
file4.close()
运行代码后d.txt文件内容:
close():把缓冲区的内容写入文件,同时关闭文件,释放文件对象相关资源
with语句(上下文管理器)不用手动关闭***
with语句可以自动管理上下文资源,不论什么原因跳出with块,都能确保文件正确地关闭,以此来达到释放资源的目的
上下文管理器:一个类对象实现了__enter__()方法和__exit__()方法,称这个类对象遵守了上下文管理协议,这个类的实例对象称为上下文管理器
with 上下文表达式(结果为上下文管理器) as src_file #同时创建一个运行时上下文,自动调用__enter__()方法,并将返回值赋值给src_file
with语句体
离开运行时上下文,自动调用上下文管理器的特殊方法__exit__()
例:
print(type(open('a.txt','r',encoding='UTF-8')))
with open('a.txt','r',encoding='UTF-8') as file:
print(file.read())
运行结果:
例:使用with复制图片
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方法被调用执行了')
with MyContentMgr() as file: #同时创建一个运行时上下文,自动调用__enter__()方法,并将返回值赋值给src_file
file.show()
#离开运行时上下文,自动调用上下文管理器的特殊方法__exit__()
运行结果:
目录/文件操作
os模块是Python内置的与操作系统功能和文件系统相关的模块,该模块中的语句的执行结果通常与操作系统有关,在不同的操作系统上运行,得到的结果可能不一样
os模块与os.path模块用于对目录或文件进行操作
import os
os.system('notepad.exe') #打开记事本
os.system('calc.exe') #打开计算器
# 直接调用可执行文件
os.startfile('D:\software\QQ\Bin\QQ.exe')
os模块操作目录的相关函数
getcwd():返回当前的工作目录
import os
print(os.getcwd())
运行结果:
listdir(path):返回指定路径下的文件和目录信息
import os
lst=os.listdir('../chap15') #../退到上级目录
print(lst)
运行结果:
例:获取指定目录下的所有.py文件
path=os.getcwd()
lst=os.listdir(path)
for filename in lst:
if filename.endswith('.py'):
print(filename)
运行结果:
mkdir(path[,mode]):创建目录
import os
os.mkdir('newdir')
运行结果:
makedirs(path1/path2…[,mode]):创建多级目录
import os
os.makedirs('A/B/C')
运行结果:
rmdir(path):删除目录
import os
os.rmdir('newdir')
运行后目录newdir已删除
removedirs(path1/path2…):删除多级目录
import os
os.removedirs('A/B/C')
运行后多级目录A/B/C已删除
chdir(path):将path设置为当前工作目录
import os
os.chdir('D:\\projects\\pythonProject\\test1\\chap1')
print(os.getcwd())
运行结果:
walk(path):遍历目录下的所有文件及目录
import os
path1=os.getcwd()
lst_files=os.walk(path1)
for dirpath,dirname,filename in lst_files:
print('===========================================')
for file in filename:
print(os.path.join(dirpath,file)) #路径名和文件名进行拼接
运行结果:
os.path模块操作目录的相关函数
abspath(path):用于获取文件或目录的绝对路径
exists(path):用于判断文件或目录是否存在,如果存在返回True,否则返回False
join(path,name):将目录与目录或者文件名拼接起来
split():分离目录与文件名
splitext():分离文件名和扩展名
basename(path):从一个目录中提取文件名
dirname(path):从一个路径中提取文件路径,不包括文件名
isdir(path):用于判断是否为目录
import os.path
print(os.path.abspath('logo.png'))
print(os.path.exists('logo.png'),os.path.exists('loho.png'))
print(os.path.join('D:\\python','logo.png'))
print(os.path.split('D:\\projects\\pythonProject\\test1\\chap15\\logo.png'))
print(os.path.splitext('D:\\projects\\pythonProject\\test1\\chap15\\logo.png'))
print(os.path.basename('D:\\projects\\pythonProject\\test1\\chap15\\logo.png'))
print(os.path.dirname('D:\\projects\\pythonProject\\test1\\chap15\\logo.png'))
print(os.path.isdir('D:\\projects\\pythonProject\\test1\\chap15\\logo.png'))
print(os.path.isdir('D:\\projects\\pythonProject\\test1\\chap14_module\\directory'))
运行结果: