在Python中将xls文件转换为csv/txt文件
我正在使用Python 2.7.3 如何将excel文件(.xls)转换为txt/.csv文件在Python中将xls文件转换为csv/txt文件,python,csv,graph,xls,Python,Csv,Graph,Xls,我正在使用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.
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
2014年7月21日0:01,0.58如果您在windows设备上或可以通过网络访问windows设备,最好的解决方案可能是编写一个Python脚本,使用子流程模块启动一个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)
上面的代码是我用来启动vbs脚本以从MS word中获取行数和字数的代码,excel应该可以实现类似的功能 使用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()
我该如何将其放入我的代码中:恐怕我在代码中看不到xls文件或csv文件的使用。嗨,hassaan_w,我已经在顶部编辑了我的初始问题,我想现在你可以看到csv文件了,因为我的文件是逗号分隔的值,我使用了错误的术语txt文件而不是csv文件谢谢你的回答。或许可以考虑添加一个解释来帮助描述代码所做的事情。
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)