文章目录
文件IO 技术
1. 创建文件对象open()
f = open("a.txt","a")
s = "你好吗?\n喜欢!\n"
f.write(s)
f.close()
1.常用编码
一字节8bit的容量是256, ASCII码用7位表示,最高位为0,所以只能表示128个字符。
一般项目都会使用UTF-8,windows 操作系统默认的编码是 GBK,Linux操作系统默认的编码是 UTF-8。
2.read()/readline()/readlines()读数据
read([s])
: 读取s个字节或字符的内容返回,默认读取到文件末尾。
readline(a)
: 读取一行的内容
readlines(a)
: 把文本文件中每一行都作为独立的字符串对象,并将这些对象放入
列表返回
3. write()/writelines()写入数据
write(a)
:把字符串a写入到文件中
writelines(b)
:把字符串列表写入文件中,不添加换行符
4. close()关闭文件流
一般结合异常机制的 finally或者with 关键字确保打开的文件对象正常关闭。
5. with语句(上下文管理器)
s = ["高淇\n","高老三\n","高老五\n"]
with open(r".\bb.txt","w") as f:
f.writelines(s)
2. 文本文件的读取
1. 文件对象的属性
f.name
: 返回文件的名字
f.mode
: 返回文件的打开模式(如r,w)
f.closed
: 若文件被关闭则返回True
2.文件对象的常用方法
非二进制文件,可以用readlines读取,用writelines写入
二进制文件,用readlines读取,用write写入
3.pickle序列化
序列化
: pickle.dump(obj, file)将obj转化成串行数据形式,存储到硬盘或传输到其他地方。
反序列
: pickle.load(file)是相反的过程,将读取到的“串行化数据”转化成对象。
import pickle
a1 = "文文"
a2 = 30
a3 = [20,30,40]
with open("b.txt","wb") as f:
pickle.dump(a1,f)
pickle.dump(a2, f)
pickle.dump(a3, f)
with open("b.txt","rb") as f:
b1 = pickle.load(f)
b2 = pickle.load(f)
b3 = pickle.load(f)
print(b1),print(b2),print(b3)
4. CSV文件的操作
CSV 文件中:
-1.值没有类型,所有值都是字符串
-2.不能指定字体颜色等样式
-3.不能指定单元格的宽高,不能合并单元格
-4.没有多个工作表
-5.不能嵌入图像图表
import csv
##########读取数据##############
with open ("abab.csv","r") as f:
a = csv.reader(f)
header = next(a) #获得标题行
print(header)
for row in a:
print(row)
#####################写入数据##################
headers = ["工号","姓名","年龄","地址","月薪"]
rows = [("1001","高淇",18,"西三旗1号院","50000"),("1002","高八",19,"西三旗1号院","30000")]
with open("a.csv","w",encoding="utf-8") as f:
b = csv.writer(f)
b.writerow(headers)
b.writerows(rows)
5.os模块
##系统命令测试
import os
#os.system("notepad.exe")
#os.system("regedit")
#os.system("ping www.baidu.com")
#os.startfile(r"D:\Program Files (x86)\Tencent\WeChat\WeChat.exe")
#print(os.name) #windows nt linux or unix posix
#print(os.sep)
#print(repr(os.linesep))
#print(os.stat("OStest1.py"))
##############关于工作目录的操作############
#print(os.getcwd()) #get current work dir
#os.chdir("d:") #change dir
#os.mkdir("书籍") #make dir
#os.rmdir("书籍") #remove dir
#os.makedirs("电影/港台/周星驰 ")
#os.removedirs("电影/港台/周星驰 ") #只能删除空目录
#os.makedirs("../音乐/香港/刘德华") #..指的是上一级目录
#os.rename("电影","movies")
print(os.listdir("movies"))
6.os.path模块
import os
from os import path
'''
print(path.isabs("d:/studyPycharm/OStest/OStest1.py")) #是否是绝对路径
print(path.isdir("d:/studyPycharm/OStest")) #是否是目录
print(path.isfile("d:/studyPycharm/OStest/OStest1.py")) #是否是文件
print(path.exists("d:/studyPycharm/OStest/OStest1.py")) #文件是否存在
print(path.getsize("a.txt"))
print(path.abspath("a.txt"))
print(path.dirname("/OStest1.py")) #输出所在目录
print(path.getctime("d:/studyPycharm/Day_10/a.txt")) #返回创建时间
print(path.getatime("d:/studyPycharm/Day_10/a.txt")) # 返回最后访问时间
print(path.getmtime("a.txt")) # 返回最后修改时间
'''
p = os.path.abspath("a.txt")
print(os.path.split(p)) # ('D:\\studyPycharm\\OStest', 'a.txt')
print(os.path.splitext(p)) # ('D:\\studyPycharm\\OStest\\a', '.txt')
print(path.join("aa","bb","cc")) # aa\bb\cc
import os
path = os.getcwd()
files = os.listdir(path)
for file in files:
if file.endswith("py"):
print(file)
print("------------------------------------------------------")
files2 = [filename for filename in os.listdir(path) if filename.endswith("py")]
for f in files2:
print(f)
7. walk()递归遍历所有文件和目录
import os
all_files = []
path = os.getcwd()
list_files = os.walk(path) #<generator object walk at 0x0000013BCC560348>
for dirpath,dirnames,filenames in list_files:
for dir in dirnames:
#print(dir)
#print(os.path.join(dirpath,dir))
all_files.append(os.path.join(dirpath,dir))
for file in filenames:
#print(file)
#print(os.path.join(dirpath,file))
all_files.append(os.path.join(dirpath,file))
for file in all_files:
print(file)
8. shutil模块(拷贝和压缩)
shutil模块提供了移动、复制、压缩、解压等操作,这些os模块都没有提供。
import shutil
#shutil.copyfile("a.txt","b.txt")
shutil.copytree("电影/港台","movies")#movies在拷贝前不存在
shutil.copytree("电影/港台","movies",ignore=shutil.ignore_patterns("*.txt","*.html"))#不想拷贝目录下的txt和html文件
压缩与解压缩
import shutil
import zipfile
#shutil.copyfile("a.txt","b.txt")
#shutil.copytree("电影/港台","movies")#movies在拷贝前不存在
#shutil.copytree("电影/港台","movies",ignore=shutil.ignore_patterns("*.txt","*.html"))#不想拷贝目录下的txt和html文件
#shutil.copytree("E:/BaiduNetdiskDownload/厚少一级下","E:/倾听者资源/英文/厚海",ignore = shutil.ignore_patterns("*.mp4"))
#压缩,解压缩
#shutil.make_archive("E:/倾听者资源/英文/厚海/listen","zip","E:/倾听者资源/英文/厚海")
#z1 = zipfile.ZipFile("a.zip","w")
#z1.write("E:/倾听者资源/英文/厚海/第十八次课")
#z1.write("E:/倾听者资源/英文/厚海/第十七次课")
#z1.write("E:/倾听者资源/英文/厚海/第十六次课")
#z1.close()
z2 = zipfile.ZipFile("D:/studyPycharm/OStest/a.zip","r")
z2.extractall("电影")
3.递归算法
阶乘算法:
def factorial(n):
if n == 1:
return 1
else:
return n*factorial(n-1)
print(factorial(5))
遍历文件递归方法:
import os
allfiles = []
def getAllFile(path,level):
childFiles = os.listdir(path)
for file in childFiles:
filepath = os.path.join(path, file)
if os.path.isdir(filepath):
getAllFile(filepath,level+1)
allfiles.append("\t"*level+filepath)
getAllFile("d:\studyPycharm",0)
for f in reversed(allfiles):
print(f)