一、遍历一个文件下的所有文件及目录
import os
for root,files,dirs in os.walk("E:\\python3.6\\work\\test",topdown=False):
print ("绝对路径是:",root)
for name in files:
print ("文件名是:",os.path.join(root,name))
for file in files:
print ("目录名是:",os.path.join(root,file))
二、找到文件test.txt所在的绝对路径
import os
for root,dirs,files in os.walk("E:\\python3.6\\work\\test",topdown=False):
for name in files:
if name=="test.txt":
print ("文件test.txt的绝对路径是:",os.path.join(root,name))
三、查找目录下.py文件个数
py_count=0
import os
for root,dirs,files in os.walk("E:\\python3.6\\work\\test",topdown=False):
for name in files:
if name[-3:]==".py":
py_count+=1
print (py_count)
四、打印一个目录下所有的文件名,不包含后缀名
result=[]
import os
for root,dirs,files in os.walk("E:\\python3.6\\work\\test",topdown=False):
for name in files:
result.append(os.path.dirname(os.path.join(root,name)))
print (result)
五、切割文件常用操作
import os
os.path.split("E:\\python3.6\\work\\b.py")
os.path.dirname("E:\\python3.6\\work\\b.py")
os.path.basename("E:\\python3.6\\work\\b.py")
os.path.splitext("E:\\python3.6\\work\\b.py")
六、将一个文件的访问时间戳换成标准格式时间
import os
os.path.getatime("E:\\python3.6\\work\\b.py")
import time
file_atime=int(os.path.getatime("E:\\python3.6\\work\\b.py"))
time_arr=time.localtime(file_atime)
time_arr
time.strftime("%Y-%m-%d %H:%M:%S")
time.strftime("%Y-%m-%d %H:%M:%S",time_arr)
用函数封装上个方法
import os,time
def time_stamp_conversion(file_path):
file_atime=int(os.path.getatime(file_path))
time_arr=time.localtime(file_atime)
print(time.strftime("%Y-%m-%d %H:%M:%S",time_arr))
if __name__=="__main__":
time_stamp_conversion("E:\\python3.6\\work\\b.py")
七、回调函数
示例一:
import os
#回调函数
def find_file(arg,dirname,files):
for file in files:
file_path=os.path.join(dirname,file)
if os.path.isfile(file_path) and (arg[0] in file or arg[1] in file) :
print ("file:%s"%file_path)
#调用
os.path.walk("E:\\python3.6\\work\\test",find_file,(".txt",".png"))
备注:该方法只适用于python2,python3版本没有os.path.walk模块
示例二:
def double(x):
return x*2
八、一个目录下建指定级数文件
import os
def create_multiple_dir(dir_path,depth,dir_name):
try:
os.chdir(dir_path)
except Exception as e:
return -1
for i in range(depth):
os.mkdir(dir_name+str(i))
os.chdir(dir_name+str(i))
with open(dir_name+str(i)+".txt","w") as fp:
fp.write(dir_name+str(i))
return 0
if __name__=="__main__":
create_multiple_dir("E:\\python3.6\\work\\test",5,"sun")
九、文件中追加内容,不存在则新建文件
import os
if os.path.exists("E:\\python3.6\\work\\test\\a.txt"):
with open("E:\\python3.6\\work\\test\\a.txt","a") as fp:
fp.write("gloryroad")
else:
with open("E:\\python3.6\\work\\test\\a.txt","w") as fp:
pass
十、序列化
import pickle
a=[1,2,3,4]
det_str=pickle.dumps(a)
print (det_str)
#将数据序列化后存储到文件中
f=open("e:\\test.txt","wb")
data={"id":1,"subject":"math","score":89}
f.write(pickle.dumps(data))
f.close()
#反序列化读取源数据
f=open("e:\\test.txt","rb")
result=pickle.loads(f.read())
print (result)
十一、统计有多少行代码
def count_code_lines_number(file_path):
line_number=0
with open(file_path) as fp:
for line in fp:
if "__" in line:
continue
elif line.strip()!="":
line_number+=1
return line_number
if __name__=="__main__":
print (count_code_lines_number("E:\\python3.6\\work\\file.txt"))
十二、在文件任意位置写入内容
def fun(file,letter,position):
with open(file) as fp:
content=fp.read()
print (len(content))
if len(content)>position:
with open(file,"r+") as fp1:
fp1.write(content[:position])
fp1.write(letter)
fp1.write(content[position:])
elif len(content)<position:
with open(file,"r+") as fp2:
fp2.write(letter)
if __name__=="__main__":
print(fun("E:\\python3.6\\work\\file.txt","gloryroad",5))