[英]Converting xls file into csv/txt file in Python
I'm Using Python 2.7.3 How can i convert excel file(.xls) to txt/.csv file我正在使用 Python 2.7.3 如何将 excel 文件(.xls)转换为 txt/.csv 文件
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('\n')
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()
sample of my txt file:我的txt文件示例:
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时间戳,辐照度 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/201 01,0.58
Use the xlrd and csv modules to convert xls to csv.使用 xlrd 和 csv 模块将 xls 转换为 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()
import pandas as pd
read_file = pd.read_excel (r' path your excel file.xlsx', sheet_name='sheet name')
read_file.to_csv (r'Path to store the text file\File name.txt', index = None, header=True)
If you are on a windows box or can access a windows box over the network the best solution maybe to write a Python script that uses the subprocess module to launches a vbscript that uses excel to export the file as a CSV file.如果您在 windows 机器上或可以通过网络访问 windows 机器,最好的解决方案可能是编写一个 Python 脚本,该脚本使用 subprocess 模块启动一个 vbscript,该脚本使用 excel 将文件导出为 CSV 文件。
def doc_count(self, path_and_file):
print("---- doc_count ----")
pprint(path_and_file)
cmd = "cscript.exe word_count.vbs \"" + path_and_file + "\" //NoLogo"
print(cmd)
result = subprocess.check_output( cmd, shell=True )
print(result)
The code above is what I use to launch a vbs script to get line and word counts out of MS Word something similar should be possible with excel.上面的代码是我用来启动 vbs 脚本以从 MS Word 中获取行和字数的代码,使用 excel 应该可以实现类似的功能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.