我有一个Excel文档,其中包含名为'foo'的行和名为'bar'的列。Foo和bar有时与'x'相关联。
我写了一些python代码,在文档中搜索'x',然后列出相关的foo和bar值。当我打印输出时,所有值都打印到控制台。当我尝试将输出存储为变量并打印变量时,我只得到最终有效的foo和bar组合。import xlrd
import csv
###Grab the data
def get_row_values(workSheet, row):
to_return = []
num_cells = myWorksheet.ncols - 1
curr_cell = -1
while curr_cell < num_cells:
curr_cell += 1
cell_value = myWorksheet.cell_value(row, curr_cell)
to_return.append(cell_value)
return to_return
file_path = 'map_test.xlsx'
myWorkbook = xlrd.open_workbook(file_path)
myWorksheet = myWorkbook.sheet_by_name('Sheet1')
num_rows = myWorksheet.nrows - 1
curr_row = 0
column_names = get_row_values(myWorksheet, curr_row)
print len(column_names)
while curr_row < num_rows:
curr_row += 1
row = myWorksheet.row(curr_row)
this_row = get_row_values(myWorksheet, curr_row)
x = 0
while x
if this_row[x] == 'x':
#print this_row[0], column_names[x]
### print this_row[0], column_names[x] works
### when I un-comment it, and prints foo and bar associated in the
### proper order
output = "[%s %s]" % (this_row[0], column_names[x])
x += 1
print output
###Using the output variable just outputs the last valid foo/bar
###combination
为什么是这样?我如何解决它?
其次,当我尝试将数据写入.csv文件时,损坏的输出将添加到.csv中,每个单元格中包含一个字符。我需要能够将每个唯一值放入其自己的单元格中,并控制它们进入的单元格。这是我到目前为止所拥有的:myData = [["number", "name", "version", "bar" "foo"]]
myFile = open('test123.csv', 'w')
with myFile:
writer = csv.writer(myFile)
writer.writerows(myData)
writer.writerows(output) ###This just outputs the last valid foo
###and bar combination
print ("CSV Written")
输出最终看起来像这样: 结果我得到了
但我希望它看起来像这样: 我想要的结果