利用os函数遍历文件夹文件统计数量

# -*- coding: utf-8 -*-
"""
Created on Mon May 27 13:05:46 2024

@author: Administrator
"""
from datetime import datetime
import os,os.path,sys
def get_filename(root_path):
    n = 0
    for root, dirs, files in os.walk(root_path, topdown = True):
        for name in files:
            rootpath = root.split("\\")
            all_path = os.path.join(root,name)
            if len(rootpath) > 2:
                print(rootpath[-2],rootpath[-1],name)
                content = rootpath[-2] + ',' + rootpath[-1] + ',' + name + ',' + all_path + '\n'
            else:
                print(root,name)
                content = root + ',' + name + ',' + all_path + '\n'
            n = n + 1
            write_list(content)
    print(n)
   

def write_list(content):
    #current_path = os.path.dirname(os.path.abspath(__file__))
    current_path = os.path.dirname(sys.argv[0])
    filename = os.path.join(current_path,start_time + '.csv')
    with open(filename, 'a', encoding='GB18030') as file:
        file.write(content)        
if __name__ == '__main__':
    root_path = r'你的路径'
    root_path = os.path.abspath(root_path)
    start_time = datetime.now().strftime("%Y%m%d%H%M%S")
    if os.path.isdir(root_path):
        get_filename(root_path)

给定一个路径统计文件写到csv文件里面,并呈现上级目录和上上级目录名和文件名以及全路径,打印文件数量不含文件夹,编码18030

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值