将变量输出写入CSV中的特定列?

时间:2018-07-19 21:03:04

标签: python excel csv xlrd scrape

我正在研究一个Python脚本,该脚本从Excel文档中抓取数据,然后将输出写入.csv。

我能够获取数据并将其写入.csv,但所有数据都进入第一列。

我需要将bar数据移至第4列并将foo数据移至第5列,因此我尝试使用csv.reader选择该行,并且该行运行时没有错误,但实际上并未写入。 csv文件。

这是我的代码:

 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'
 output = []
 output_bar = []
 output_foo = []

 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':
                    output.append([this_row[0], column_names[x]])
                    output_bar.append([column_names[x]]) 
                    output_foo.append([this_row[0]])
                    print output
                    myData = [["number", "name", "version", "bar", 
 "foo"]]

                    ##### Next section is the code in question, it 
 ####doesn't error out, but won't write to the .csv######

                myFile = open("test123.csv", "w")
                writer = csv.writer(myFile)
                with open('test123.csv', 'r') as csvfile:
                    reader = csv.reader(csvfile, delimiter=',')
                    for row in reader:
                        row[5] = myFile.readline()
                        writer.writerows(output_foo)
                        row[4] = myFile.readline()
                        writer.writerows(outpu_bar)

                        #####This successfully writes to the csv, but      
 #####all data to first column#####

    #           myFile = open('test123.csv', 'w')
    #           with myFile:
    #                   writer = csv.writer(myFile)
    #                   writer.writerows(myData)
    #                   #writer.writerows(output)
    #                   writer.writerows(output_foo)
    #                   writer.writerows(output_bar)

            x += 1

 print ("CSV Written")

0 个答案:

没有答案