Python编程之获取目录下csv文件名

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010896233/article/details/79979596
#!/usr/bin/python
# -*- coding:utf-8 -*-

import os
import fnmatch
import time
import re
import winreg

print('* * * * * * * * * * * * * * * * * * * * * * * * * * * * *')
print('---------------文件类型输入格式为:*.XXX-----------------')
print('----------文件类型输入*表示显示目录下所有文件------------')
print('------------文件路径格式电脑文件路径显示方式-------------')
print('------------------例如:C:\Desktop-----------------------\n------------------------*.csv----------------------------')
print('------------脚本执行后所产生的数据将新建一个CSV文件夹存放在桌面上-------------')
print('* * * * * * * * * * * * * * * * * * * * * * * * * * * * *')


class FindFiles:

    def __init__(self, path, type_str):

        if path is '':
            self.path = 'C:\Desktop'
        else:
            self.path = path
        if type_str is '':
            self.type_str = '*.csv'
        else:
            self.type_str = type_str

    def get_desktop(self):
        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER,r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders')  # 利用系统的链表
        return winreg.QueryValueEx(key, "Desktop")[0]  # 返回的是Unicode类型数据

    def filePath(self):
        filelist = []
        fndatalist = []
        localtime = time.strftime('%Y_%m_%d %H:%M:%S', time.localtime(time.time()))  # 显示当地时间
        print(localtime)
        print('PATH:%s     FilesType:%s' % (self.path, self.type_str))

        Desktop_path = str(self.get_desktop())
        mkpath = Desktop_path + '\CSV\NewData'
        if os.path.exists(mkpath) is False:  # 判断一个目录是否存在
            os.mkdir(mkpath + '\\')  # 创建目录,用于存放处理后的数据

        fo = open(mkpath+'\\'+'listfile.txt', 'wb')
#        fo.write(localtime + "\r\n")
        fnlist = os.walk(self.path)

        for root, dirs, files in fnlist:
            pass

        if self.type_str == '*.csv':
            for i in fnmatch.filter(files, self.type_str):
                filelist.append(i)
            print len(filelist)

            filelist.sort(key=len)
            print len(filelist)
            for fnitem in filelist:
                fo.write(fnitem + '\r\n')  # 写入的是文件名

            for allfilename in filelist:
                fn = '%s/%s' % (root, allfilename)
                fn = fn.replace('/', '\\')
                fndatalist.append(fn)
            return filelist
        fo.close()

if __name__ == '__main__':
    root = raw_input('PATH:')
    type_str = raw_input('FilesType(default:*.csv):')

    a = FindFiles(root, type_str)
    filenamelist = a.filePath()
    print(filenamelist)

input('Please ENTER to END')#这里的输入无意义,主要是为了不让控制台闪退
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页