python pands实现execl转csv 并修改csv指定列的方法

yipeiwu_com6年前Python基础

如下所示:

# -*- coding: utf-8 -*-
import os 
import pandas as pd
import numpy as np
#from os import sys

def appendStr(strs):
 return "BOQ" + strs

def addBOQ(dirs, csv_file):
 data = pd.read_csv(os.path.join(dirs, csv_file), encoding="gbk")
 data = data[data[u"BOQ条码"] != 'None']
 data[u"BOQ条码"] = data[u"BOQ条码"].astype(np.str)
 data[u"BOQ条码"] = data[u"BOQ条码"].apply(appendStr, 1)
 data.to_csv(os.path.join(dirs, csv_file), index=False, encoding="gbk")

def execl2csvbypandas(dirs, excel_file, addStr):
 newdir = os.path.join(dirs, "csvdir")
 if not os.path.isdir(newdir):
  os.makedirs(newdir)
 filename = os.path.splitext(excel_file)
 data_xls = pd.read_excel(os.path.join(dirs, excel_file), 'Sheet1', index_col=0)
 csvname = os.path.join(newdir, filename[0].join(['sheet1', '.csv']))
 data_xls.to_csv(csvname, encoding='gbk')
 if True == addStr:
  addBOQ(newdir, csvname)

def procExeclFiles(arg, dirs, files):
 print arg
 for f in files:
  file_path = os.path.join(dirs, f)
  if os.path.isfile(file_path):
   print f
   execl2csvbypandas(dirs, f, arg)
 print "end...."

 
if __name__ == "__main__":
 #遍历目录,并把改目录下的execl转为csv,然后存入该目录下csvdir目录下,传参数True时,是给csv中BOQ条码列添加BOQ字符串,一般为False
 os.path.walk(r"C:\Users\Desktop\test", procExeclFiles, (True))

以上这篇python pands实现execl转csv 并修改csv指定列的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python实现删除文件但保留指定文件

由于给客户的发布版本上客户改动了些代码和图片,我们这边给他们更新publish都是增量更新(开发提供更新指定的文件,我们提取出来给客户进行覆盖更新),但有时需要更新的文件较多导致不得不一...

python排序方法实例分析

本文实例讲述了python排序方法。分享给大家供大家参考。具体如下: >>> def my_key1(x): ... return x % 10 ... >...

python字符串str和字节数组相互转化方法

实例如下: # bytes object b = b"example" # str object s = "example" # str to bytes bytes(...

Python入门_浅谈for循环、while循环

Python入门_浅谈for循环、while循环

Python中有两种循环,分别为:for循环和while循环。 1. for循环 for循环可以用来遍历某一对象(遍历:通俗点说,就是把这个循环中的第一个元素到最后一个元素依次访问一次)...

python数据结构之链表的实例讲解

python数据结构之链表的实例讲解

在程序中,经常需要将⼀组(通常是同为某个类型的)数据元素作为整体 管理和使⽤,需要创建这种元素组,⽤变量记录它们,传进传出函数等。 ҳ...