在Python中将xls文件转换为csv/txt文件
我正在使用 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()
这是我 txt 文件的一个例子:
时间戳, 辐照度
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
3 个回答
-1
如果你在使用Windows电脑,或者可以通过网络访问一台Windows电脑,最好的办法可能是写一个Python脚本。这个脚本会用到一个叫做subprocess的模块,它可以启动一个VBScript,然后这个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)
上面的代码是我用来启动一个VBScript的,它可以从MS Word中获取行数和单词数。用类似的方法也应该可以在Excel中实现。
0
在编程中,有时候我们会遇到一些问题,尤其是在使用某些工具或库的时候。这些问题可能会让我们感到困惑,特别是当我们刚开始学习编程的时候。比如,有些错误信息可能会很复杂,让人不知道该怎么解决。
在这种情况下,查看其他人遇到的类似问题和解决方案就显得特别重要。像StackOverflow这样的平台就是一个很好的地方,大家可以在这里提问和回答问题。通过阅读别人的经验,我们可以更快地找到解决办法,避免走弯路。
总之,遇到问题时,不要害怕去寻求帮助,利用好网络资源,学习别人的解决方案,这样可以帮助我们更好地理解编程的世界。
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)
7
使用 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()