利用python扫描文件和目录

写这个简单小工具的目的是研究python,觉得写这种程序是脱裤子放屁的人请绕道~

工作中经常需要分离大批量的路径名和文件名并将其置入一个特殊格式的文档,所以在研究python的同时写了这个小工具,貌似也算跨平台了吧。大笑

 

功能:

扫描指定文件夹,遍历文件夹所有文件,将文件路径和文件名分开存储到xls文件中进行二次处理。

 

Windos XP,7 + Python 2.6编译通过。

#Name:File Scan
#Description:Scan files and write the full path to xls file
#Auhor:Carl Liu
#Date:2013-4-23
#Update:2013-4-23

import sys
import os
import os.path
import xlrd
import xlwt

#Go through dir function
#use xlwt to wirte record set to xls file
def dirscan(path_list):
    xls_path=os.getcwd()
    xls_path+="\\output_list.xls"   #Store result xls to the folder which contain this programme 
    xfile=xlwt.Workbook()
    print("File and path will be stored in:"+xls_path)
    table=xfile.add_sheet("files",cell_overwrite_ok=True) #Let the xls file could overwrite if it exists or already contain some data.
    row=0
    col=0
    for p in path_list:
        for parent,dirname,filenames in os.walk(p):
            for filename in filenames:
                print(str(col)+"\t"+parent+"\t\t"+filename)
                table.write(col,0,parent)
                table.write(col,1,filename)
                col+=1
    xfile.save(xls_path)
    print("Total file number:"+str(col))

#Handle passin parameter
def argvs(parameter):
    path=[]
    if len(parameter)==1:       #At least will pass its self path
        path.append(os.getcwd())
    else:
        if len(parameter)==2:   #Deal with the real parameter
            path.append(parameter[1])
        else:
            path=parameter[1:]  #more than one parameter
    return path

#main function for python
if __name__=="__main__":
    root_path=[]#Store path as list
    print("Programe Start!")
    root_path=argvs(sys.argv)#Handle Parameter
    for dir_path in root_path:
        print(dir_path)
    print("File list had been extract to xls file:")
    dirscan(root_path)
    print("Programe End!")


使用方法:

将python源程序拷贝到目的文件夹,双击即可。

或者使用command line:py filename.py [target dest1] [traget dest2]

可以指定扫描目标,如果不指定,那么默认扫描程序所在文件夹。

 

即使是这样的小程序也是有瑕疵的,欢迎大家帮助指正改进。
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值