文件目录操作练习一

这篇博客涵盖了Python中处理文件和目录的各种操作,包括遍历目录、查找特定文件、统计.py文件数量、获取文件时间戳、创建多级目录、文件追加内容、序列化和反序列化以及代码行数统计等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、遍历一个文件下的所有文件及目录

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))

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值