在 Python 中将 xls 文件转换为 csv/txt 文件 [英] Converting xls file into csv/txt file in Python

查看:42
本文介绍了在 Python 中将 xls 文件转换为 csv/txt 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是 Python 2.7.3我如何将 excel 文件(.xls)转换为 txt/.csv 文件

I'm Using Python 2.7.3 How can i convert excel file(.xls) to txt/.csv file

import matplotlib.pyplot as plt

x = []
y = []
t = []

fig = plt.figure()
rect = fig.patch
rect.set_facecolor('#31312e')

readFile = open('data.csv', 'r')
sepFile = readFile.read().split('
')
readFile.close()

for idx, plotPair in enumerate(sepFile):
    if plotPair in '. ':
       # skip. or space
       continue
    if idx > 1:  # to skip the first line
        xAndY = plotPair.split(',')
        time_string = xAndY[0]
        t.append(time_string)
        y.append(float(xAndY[1]))

ax1 = fig.add_subplot(1, 1, 1, axisbg='blue')
ax1.plot(t, y, 'c', linewidth=3.3)

plt.title('IRRADIANCE')
plt.xlabel('TIME')

plt.show()

我的 txt 文件示例:

sample of my txt file:

时间戳,辐照度21/7/2014 0:00,0.6621/7/2014 0:00,0.7121/7/2014 0:00,0.6521/7/2014 0:00,0.6721/7/2014 0:01,0.58

TimeStamp,Irradiance 21/7/2014 0:00,0.66 21/7/2014 0:00,0.71 21/7/2014 0:00,0.65 21/7/2014 0:00,0.67 21/7/2014 0:01,0.58

推荐答案

使用 xlrd 和 csv 模块将 xls 转换为 csv.

Use the xlrd and csv modules to convert xls to csv.

import xlrd
import csv

def xls_to_csv():

    x =  xlrd.open_workbook('data.xls')
    x1 = x.sheet_by_name('Sheet1')
    csvfile = open('data.csv', 'wb')
    writecsv = csv.writer(csvfile, quoting=csv.QUOTE_ALL)

    for rownum in xrange(x1.nrows): #To determine the total rows. 
        writecsv.writerow(x1.row_values(rownum))

    csvfile.close()

这篇关于在 Python 中将 xls 文件转换为 csv/txt 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆