写这个简单小工具的目的是研究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]
可以指定扫描目标,如果不指定,那么默认扫描程序所在文件夹。
即使是这样的小程序也是有瑕疵的,欢迎大家帮助指正改进。