【发布时间】:2018-12-25 17:37:47
【问题描述】:
我有一个 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 <len(this_row):
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")
输出最终看起来像这样: Results I'm getting
但我希望它看起来像这样: Results I want
【问题讨论】: