利用os.walk生成当前目录及其下层目录的文件列表

 该程序支持:

(1)python script_name.py。把当前目录及其下层目录中所有文件联合文件的路径写入一个文件中;

(2)python script_name.py output_file_name。指定输出的文件名。

import os
import sys

def get_file_with_path(file_path) :
    file_path_list = []

    for root,dirs,files in os.walk(file_path) :
        if (len(files) != 0) :
            for file in files :
                #filter the temporary files
                if file.endswith('.swp') == False :
                    file_path = os.path.join('%s\%s'%(root,file))
                    if os.path.isfile(file_path) :
                        file_path_list.append(file_path)

    return file_path_list

if __name__ == '__main__' :
    curr_path = os.getcwd()
    file_path_list = []
    file_path_list = get_file_with_path(curr_path)

    #write all the file with path into one file
    if len(sys.argv) == 1 :
        with open('file_list.f','w') as file_handle :
            for file_path in file_path_list :
                file_handle.write("%s\n"%file_path)
    else :
        #get the input file name
        file_output_name = sys.argv[1]
        with open('%s'%file_output_name,'w') as file_handle :
            for file_path in file_path_list :
                file_handle.write("%s\n"%file_path)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值