写一个python脚本来抓取excel数据并写入CSV,我如何获得正确的输出



我有一个Excel文档,行名为"foo",列名为"bar"。Foo和bar有时与"x"联系在一起。

FooBar Tracker Excel文档

我编写了一些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")

输出结果如下所示:结果我得到

但我希望它看起来像这样:结果我想要

您的output变量(您的累加器(不是不断地添加值,而是在每次循环运行时重写行、列的值。print语句之所以有效,是因为它对每次循环运行都进行打印,这就是您所看到的。

要修复此问题,请将输出变量设置为while循环之外的空列表:

output = []

然后更改这一行:

output = "[%s %s]" % (this_row[0], column_names[x]) 

对此:

output.append([this_row[0], column_names[x]]) 

你遇到的另一个问题是你的输出很有趣。这是因为这条线:

output = "[%s %s]" % (this_row[0], column_names[x]) 

您要求python将this_row呈现为字符串,然后在位置[0]中给您一个字符,很可能只是"f"。上面对代码的更改也修复了这个问题。

附带说明一下,使用for循环而不是while循环会被认为是更好的形式。例如

for row in range(0,num_rows) :

最新更新