1.基本文件的写入:创建文件对象,写入数据,关闭文件
2.用writelines()输入时想要换行需要自行添加换行符
3.finally异常机制确保文件一定会被关闭
try:
f = open(r"a.txt","a")
s=" i love python"
f.write(s)
except BaseException as e:
print (e)
finally:
f.close()
4.with可以自动关闭现场,用的最多
with open(r"b.txt","w") as f:
f.writelines(" i love python")
5.文件读取
使用迭代器(每次返回一行)读取文本文件
with open(r"a.txt","r") as f:
for a in f:
print (a,end=" ")
6.enumerate()与推导式
with open(r"b.txt","r",encoding="utf-8") as f:
lines=f.readlines()
#推导式生成列表
lines=[line.rstrip() + "#" + str(index+1) for index, line in enumerate(lines)]
with open("b.txt","w",encoding="utf-8") as f:
f.writelines(lines)
7.二进制文件
8.测试seek(),tell()
with open(r"b.txt","r",encoding="utf-8") as f:
print("文件名:{0}".format(f.name))
print(f.tell())
print("读取的内容:{0}".format(str(f.readline())))
print(f.tell())
print("读取的内容:{0}".format(str(f.readline())))
#偏移3个字符
f.seek(3,0)
print("读取的内容:{0}".format(str(f.readline())))
结果:
文件名:b.txt
0
读取的内容:i love you#1
14
读取的内容:python#2
读取的内容:ove you#1
进程已结束,退出代码0
9.pickle序列化
import pickle
a1="i"
a2="love"
a3=[10,20,30,40]
with open("b.dat","wb") as f:
pickle.dump(a1,f)
pickle.dump(a2, f)
pickle.dump(a3, f)
with open("b.dat","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))
结果:
i
love
[10, 20, 30, 40]
1696531776096
1696531776096
进程已结束,退出代码0
10.CSV文件的读写
import csv
#读取CSV文件
with open("e.csv","r",encoding="utf-8") as f:
a_csv=csv.reader(f)
for row in a_csv:
print(row)
#写入CSV文件
with open("a.csv","w",encoding="utf-8") as f:
b_csv=csv.writer(f)
b_csv.writerow(["ID","姓名","年龄","工资"])
b_csv.writerow(["1001", "lila", "18","22"])
结果;
['ID', '姓名', '年龄', '工资']
['1001', 'Lily', '19', '20']
['1002', 'Bob', '20', '24']
['1003', 'Cris', '18', '21']
['1004', 'Jordan', '19', '22']
11.os模块
import os
#os.system("notepad.exe")
os.system("ping www.baidu.com")
12.os.path模块
import os
import os.path
#######判断:绝对路径,是否目录,是否文件,文件是否存在######
print(os.path.isabs("d:/a.txt"))
print(os.path.isdir("d:/a.txt"))
print(os.path.isfile("d:/a.txt"))
print(os.path.exists("d:/a.txt"))
##############获取文件信息###############################
print(os.path.getsize("a.txt"))
print(os.path.abspath("a.txt"))
print(os.path.getctime("a.txt"))
print(os.path.getatime("a.txt"))
print(os.path.getmtime("a.txt"))
13.os.walk()方法
import os
all_files=[]
path=os.getcwd()
list_files=os.walk(path)
for dirpath,dirnames,filenames in list_files:
for dir in dirnames:
print(os.path.join(dirpath,dir))
for file in filenames:
print(file)
#打印所有子目录和子文件
for file in all_files:
print(file)
14shutil模块
import shutil
shutil.copyfile("a.txt","a1.txt")#拷贝a1
shutil.copytree("1/h222","newfile")
shutil.copytree("1/h222","newfile",ignore=shutil.ignore_patterns(("*.txt"))
15.递归调用
#递归打印所有的目录和文件
import os
allfiles=[]
def getAllfiles(path,level):
childFiles=os.listdir(path)
for file in childFiles:
filepath=os.path.join(path,file)
if os.path.isdir(filepath):
getAllfiles(filepath,level+1)
allfiles.append("\t"*level+path)
getAllfiles("D:\pythonProject",0)
for f in reversed(allfiles):
print(f)