[英]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.