[英]Python - Using csv and xlrd module to write multi-row excel file to one row csv file
我有一个基本脚本,它将使用源excel(.xlsx)文件并将数据写入python中匹配的csv文件中。 我的最终目标是将所有数据放在一张工作表中,然后将其写成一个长逗号分隔的行,我不确定如何根据目前的情况来完成该工作。
def csv_from_excel():
import csv
import xlrd
wb1 = raw_input('What is the path and file name of your Workbook? ')
sh = raw_input('What is the name of the sheet being transformed? ')
csv_file1 = raw_input('What is the file path and name of the output? ')
print wb1
print sh
print csv_file1
wb = xlrd.open_workbook(wb1)
sh1 = wb.sheet_by_name(sh)
csv_file = open(csv_file1, 'wb')
wr = csv.writer(csv_file, quoting=csv.QUOTE_MINIMAL)
for rownum in xrange(sh1.nrows):
wr.writerow(sh1.row_values(rownum))
csv_file.close()
print "Completed converting %s and %s to csv" % (wb1, sh)
csv_from_excel()
如果我理解正确,则需要采用多行XLS并将其输出为单行CSV。 如果是这样,这将导致您输出多个CSV行:
for rownum in xrange(sh1.nrows):
wr.writerow(sh1.row_values(rownum))
该代码逐步遍历XLS中的每一行,并在CSV中创建相应的行。 由于您只需要一个CSV行,因此您可能应该在一步中将所有XLS行写出之前将其累积到一个集合中:
output = list()
for rownum in xrange(sh1.nrows):
output.extend(sh1.row_values(rownum))
wr.writerow(output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.