文件操作(IO技术)
文本文件和二进制文件
文本文件:用于存储字符的文件,默认使用Unicode字符集(采用两个字节表示一个符号,最多可以表示2E16次方个)
二进制文件:无法用记事本打卡,使用“字节”进行存储
文件操作相关模块
io模块
os模块
glob模块
创建文件对象open()
语法格式:
open(文件名[打开方式])
打开方式:
r 读模式
w 写模式(创建或重写)
a 追加模式(创建或文尾追加内容)
b 二进制模式
- 读写模式(可与其它模式组合使用)
文本文件的写入
基本文件写入操作:
1.创建文件对象
2.写入数据
3.关闭文件对象
write()/writelines()写入数据
write(a):把字符串a写入文件中
writelines(b):
close()关闭文件流
try:
f = open(r'003.txt','a')
str = 'Beautiful Liu'
f.write(str)
except BaseException as e:
print(e)
finally:
f.close()
with语句(上下文管理器)
不论什么原因跳出with模块,都能确保文件正确地关闭,且在该代码执行完毕后自动还原到进入该模块前的状态
with open(r'004.txt','a') as f:
f.write('Liumeili, you are really meili')
文本文件读取
1.read([size]):文件中读取size个字符串,没有size参数则读取整个文件
2.readline():读取一行内容作为返回值。读到文尾则返回空字符串
3.readlines()
with open(r'005.txt','a') as f:
f.write('I love U!\n')
f.write('Happy Progranner!\n')
print('---------read-----------')
with open(r'005.txt','r') as f:
str = f.read(5)
print(str)
print('--------按行读取--------')
with open(r'005.txt','r') as f:
while True:
fragement = f.readline()
if not fragement:
break
else:
print(fragement,end='')
print('-------使用迭代器-------')
with open(r'005.txt','r') as f:
for a in f:
print(a,end='')
enumerate()
with open('005.txt','r') as f:
lines = f.readlines()
lines = [ line.rstrip() +' #'+ str(index+1)+'\n' for index,line in enumerate(lines)]
with open('005.txt','w') as f:
f.writelines(lines)
二进制文件的读写
打开方式+b:
rb 读模式
wb 写模式(创建或重写)
ab 追加模式(创建或文尾追加内容)
文件对象的常见属性和方法
with open('005.txt','r') as f:
print('文件名是{0}'.format(f.name))
print(f.tell())
print('读取内容:{0}'.format(f.readline()))
print(f.tell())
使用pickle序列化
序列化是指将对象转化成“串行化”数据形式,以存储到硬盘或通过网络传输到其他地方。反序列化是指相反的过程,将读取到的“串行化数据”转化为对象。
使用pickle模块中的函数可以实现序列化和反序列化的操作。
序列化语法:
pickle.dump(obj,file) obj:序列化的对象,file:存储的文件
pickle.load(file) 从序列中读取数据,反序列化成对象
import pickle
a1 = 'Meili'
a2 = 433
a3 = [10,30,45]
with open(r'001.txt','wb') as f:
pickle.dump(a1,f)
pickle.dump(a2,f)
pickle.dump(a3,f)
with open('001.txt','rb') as f:
b1 = pickle.load(f);b2 = pickle.load(f);b3 = pickle.load(f)
print(b1);print(b2);print(b3)
print(id(a1));print(id(b1))
CSV文件的操作
CSV常用于数据交换,Excel文件和数据库数据的导入和导出。
CSV文件中:
- 值没有类型,所有值都是字符串;
- 不能指定字体颜色等样式;
- 不能指定单元格的宽高,不能合并单元格;
- 没有多个工作表;
- 不能嵌入图像图表.
import csv
with open('002.csv','r') as f:
a_csv = csv.reader(f)
#print(list(a_csv))
for row in a_csv:
print(row)
with open('002_1.csv','w') as f:
b_csv = csv.writer(f)
b_csv.writerow(['id','name','age'])
b_csv.writerow(['3121','Meili','19'])
c = [['31231','Cute','43'],['43214','fds','23']]
b_csv.writerows(c)
os模块和os.path模块
os:操作系统
os模块直接对操作系统进行操作,可直接调用操作系统的可执行文件,命令,直接操作文件,目录等。
os调用操作系统文件和命令
os.system:直接调用系统的命令
os 模块-文件和目录操作
import os
#####获取文件和文件夹中相关的信息#########
print(os.name) #windows-->nt,linux和unix-->posix
print(os.sep) #windoes-->\ linux和unix-->/
print(repr(os.linesep)) #windows-->\r\n linux-->\n\
print(os.stat('mypy002.py'))
##########关于工作目录的操作###########
print(os.getcwd())
os.chdir('d:') #改变当前工作目录为:d盘根目录
print(os.getcwd())
#os.mkdir('书籍')
############创建目录,多级目录,删除########
#os.mkdir('书籍')
#os.rmdir('书籍')#相对路径都是当前的工作目录
#os.makedirs('电影/港台/周星驰')
os.makedirs('movie/日韩')
#os.removedirs('电影/港台/周星驰')#只能删除空目录
#os.makedirs('../music/HongKong/Dehua Liu')#../指的是上级目录
#os.rename('电影','movie')
dirs = os.listdir('movie')
print(dirs)
os.path提供目录相关的操作
包括:路径判断,路径切分,路径链接,文件夹遍历
with open('003.txt','w') as f:
f.write('Happy everyday!')
import os
import os.path
###########判断:绝对路径,是否目录,是否文件,是否存在#########
print(os.path.isabs('003.txt'))
print(os.path.isfile('003.txt'))
print(os.path.exists('003.txt'))
#######获得文件基本信息#############
print(os.path.getsize('003.txt'))
print(os.path.abspath('003.txt'))
print(os.path.dirname('d:/PycharmProjects/MyDemo/TestOs/003.txt'))
print(os.path.getctime('003.txt'))
print(os.path.getatime('003.txt'))
print(os.path.getmtime('003.txt'))
############对路径的操作##########
path = os.path.abspath('003.txt')
print(os.path.split(path))
print(os.path.splitext(path))
print(os.path.join('aa','bb','cc'))
import os
path = os.getcwd()
file_list = os.listdir(path)#列出子列表,子文件
for filename in file_list:
if filename.endswith('py'):
print(filename)
print('-----------------------')
file_list2= [filename for filename in os.listdir(path) if filename.endswith('py')]
for f in file_list2:
print(f,end='\t')
walk()递归遍历所有文件和目录
os.walk():返回含有三个元素的元组。(dirpath,dirnames,filenames)
dirpath:指定目录路径
dirnames:目录下所有文件夹
filenames:目录下所有文件
import os
all_files = []
path = os.getcwd()
list_files = os.walk(path)
for dirpath,dirnames,filenames in list_files:
for dir in dirnames:
all_files.append(os.path.join(dirpath,dir))
"""print(dir)
print('-----------path.join-----')
print(os.path.join(dirpath,dir))"""
for file in filenames:
all_files.append(os.path.join(dirpath,file))
"""print(file)
print('------file.join----------')
print(os.path.join(dirpath,file))"""
#打印所有子文件和子目录
for file in all_files:
print(file)
shutil模块(拷贝和压缩)
文件和文件夹的拷贝,及压缩操作(os模块的补充)
shutile.make_archive (压缩包所在位置及名字,压缩包格式,要压缩的内容)
zip.ZipFile
import shutil
import zipfile
#shutil.copyfile('001.txt','001_copy.txt')
#shutil.copytree('movie/港台','电影',ignore=shutil.ignore_patterns('*.txt')) #只能拷贝到一个新目录中
#压缩
#shutil.make_archive('电影/gg','zip','movie/港台')
z1 = zipfile.ZipFile('a.zip','w')
z1.write('001.txt')
z1.close()
#解压缩
z2 = zipfile.ZipFile('a.zip','r')
z2.extractall('电影')
z2.close()
递归算法
自己调用自己
import os
allfiles = []
def getAllFiles(path,level):
childFile = os.listdir(path)
for file in childFile:
filepath = os.path.join(path,file)
if os.path.isdir(filepath):
getAllFiles(filepath,level+1)
allfiles.append('\t'*level+filepath)
getAllFiles('movie',0)
for f in allfiles:
print(f)