#!/usr/bin/env python
__author__ = "
lrtao2010
"'''
excel檔案轉csv檔案指令碼
需要將該指令碼直接放到要轉換的excel檔案同級目錄下
支援xlsx 和 xls 格式
在同級目錄下生成名為excel_to_csv.csv 的檔案,採用utf-8編碼
'''import
xlrd
import
csvimportos#
生成的csv檔名
csv_file_name = '
excel_to_csv.csv
'def
get_excel_list():
#獲取excel檔案列表
excel_file_list =
file_list =os.listdir(os.getcwd())
for file_name in
file_list:
if file_name.endswith('
xlsx
') or file_name.endswith('
xls'
):
return
excel_file_list
defget_excel_header(excel_name_for_header):
#獲取表頭,並將表頭全部變為小寫
workbook =xlrd.open_workbook(excel_name_for_header)
table =workbook.sheet_by_index(0)
#row_value = table.row_values(0)
row_value = [i.lower() for i in
table.row_values(0)]
return
row_value
defread_excel(excel_name):
#讀取excel檔案每一行內容到乙個列表中
workbook =xlrd.open_workbook(excel_name)
table = workbook.sheet_by_index(0) #
讀取第乙個sheet
nrows =table.nrows
ncols =table.ncols
#跳過表頭,從第一行資料開始讀
for rows_read in range(1,nrows):
#每行的所有單元格內容組成乙個列表
row_value =
for cols_read in
range(ncols):
#獲取單元格資料型別
ctype =table.cell(rows_read, cols_read).ctype
#獲取單元格資料
nu_str =table.cell(rows_read, cols_read).value
#判斷返回型別
#0 empty,1 string, 2 number(都是浮點), 3 date, 4 boolean, 5 error
#是2(浮點數)的要改為int
if ctype == 2:
nu_str =int(nu_str)
yield
row_value
defxlsx_to_csv(csv_file_name,row_value):
#生成csv檔案
with open(csv_file_name, '
a', encoding='
utf-8
',newline='') as f: #
newline=''不加會多空行
write =csv.writer(f)
write.writerow(row_value)
if__name__ == '
__main__':
#獲取excel列表
excel_list =get_excel_list()
#獲取excel表頭並生成csv檔案標題
xlsx_to_csv(csv_file_name,get_excel_header(excel_list[0]))
#生成csv資料內容
for excel_name in
excel_list:
for row_value in
read_excel(excel_name):
xlsx_to_csv(csv_file_name,row_value)
print('
excel檔案轉csv檔案結束
')
批量將CSV檔案轉為excel
import os import pandas as pd fp r c users jjjj desktop 233 for root,dirs list,files list in os.walk fp root 表示當前資料夾路徑 dirs 當前資料夾下所有子目錄名 files 當前資料夾下所...
python將arff檔案轉為csv檔案
資料集有可能是以arff格式 weka用的 儲存,一般的機器學習使用numpy,pandas和sklearn多一些,無法直接讀取檔案,所以需要scipy.io.arff.loadarff過渡下。from scipy.io import arff import pandas as pd file na...
python xls檔案轉為csv
import pandas as pda ex pda.read excel k.xls ex.to csv k.csv encoding gbk 很多檔案轉為csv檔案時,encoding utf 8 時會出現亂碼,所以我才會選擇使用gbk。同理,csv轉為xls也是一樣的。import pand...