i-orange

以后再追加注释

#! python3
\'\'\'
Author: i_orange

将csv转为xlsx的小程序

\'\'\'
import csv, openpyxl, os, time

def convert():
    pass

print(\'%%请将要转换的csv文件放置到空文件夹下%%\')

path = input(\'请输入csv文件所在文件夹路径:\')

pathList = path.split(os.sep)
newPath = (os.sep).join(pathList)

#0.切换到工作目录
os.chdir(newPath)

#1.程序计时
start = time.clock()
data = time.strftime(\'%Y%m%d%H%M%S\')

#2. 计数
count = 1

#2.创建处理后的保存目录
newDir = [\'转换后\',data]
pathList.extend(newDir)

newPath1 = (os.sep).join(pathList)
os.makedirs(newPath1,exist_ok = True)

#3.列出工作目录下的文件
for folderName, subFolderNames, fileNames in os.walk(newPath):
##    print(\'当前所在文件夹名称:\'+ folderName)
    #子文件夹
    for subFolderName in subFolderNames:
##        print(\'包含的子文件夹有:\'+ subFolderName)
        pass

    #子文件
    for fileName in fileNames:
##        print(\'包含的文件有:\' + fileName)

        if fileName.endswith(\'csv\'):
            #创建空的xlsx
            wb = openpyxl.Workbook()
            sheet = wb.create_sheet()
            sheet.title = \'Sheet1\'

            del wb[\'Sheet\']
            #
            with open(fileName,\'r\') as f:
                lines = csv.reader(f)
                i = 1

                for k,line in enumerate(lines):
##                    print(k)
                    numLines = len(line)    #列数
                    for j in range(0,numLines):
                        try:
                            sheet.cell(row=k+1,column=j + 1).value = float(line[j])
                        except ValueError:
                            sheet.cell(row=k+1,column=j + 1).value = line[j]
                wb.save(newPath1 + os.sep + fileName.split(\'.csv\')[0] + \'.xlsx\')
                count += 1
                print(fileName + \'转换完成\')
    end = time.clock()
print(\'数据处理耗时:%f s \n处理文件数:%d\' %((end-start),count))

 

分类:

技术点:

相关文章:

  • 2022-01-22
  • 2022-01-29
  • 2021-06-27
  • 2022-12-23
  • 2022-12-23
  • 2021-06-13
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-19
  • 2022-01-10
  • 2021-07-05
  • 2022-01-09
  • 2022-12-23
相关资源
相似解决方案