简体   繁体   English

如何在附加 xlrd 单元格值 Python 时使用 csv writerow

[英]How to use csv writerow while appending xlrd cell value Python

I wrote the following function that copies data from numerous excel files and copies them to csv.我编写了以下 function,它从众多 excel 文件中复制数据并将它们复制到 csv。 I am having trouble appending the "refresh_date_value" from a single cell in excel and iterating with writerow to include that date value with every row in my csv output.我无法从 excel 中的单个单元格中附加“refresh_date_value”,并使用 writerow 迭代以将该日期值包含在我的 csv Z78E6221F6393D1356681DB398F14CE6 中的每一行中。 Currently it takes the "refresh_date_value" and splits every character into seperate columns.目前它采用“refresh_date_value”并将每个字符拆分为单独的列。 For example, the output files puts every character in its own column [2, 0, 2, 0, /, 0, 6....].例如,output 文件将每个字符放在自己的列 [2, 0, 2, 0, /, 0, 6....]。 I'd just like to have the entire date in one column for each row.我只想将整个日期放在每一行的一列中。 The "refresh_date_value" is a date time object so I didn't know how to join in writerow without turning it into a list. “refresh_date_value”是日期时间 object 所以我不知道如何加入 writerow 而不把它变成一个列表。 I've found some examples on Stack similar, but have been unable to get the desired results.我在 Stack 上找到了一些类似的示例,但一直无法获得预期的结果。 Thank you in advance.先感谢您。

''' '''

def append_all(input_directory):
    for file in os.listdir(input_directory):
        if bool(re.search(pattern, file)) == True:
            in_fpath = os.path.join(input_directory, file)
            out_fpath = os.path.join(input_directory, 'history.csv')
            wrkbk = xlrd.open_workbook(in_fpath)
            wrksht = wrkbk.sheet_by_name('importer')
            
            refresh_date_float = wrksht.cell_value(1,4)
            refresh_date_value = xlrd.xldate_as_datetime(refresh_date_float, wrkbk.datemode).strftime('%Y/%m/%d %H:%M')
            
            if os.path.isfile(out_fpath) == False:
                with open(out_fpath, 'w', newline='') as csvfile:
                    wr = csv.writer(csvfile)
                    for rownum in range(3, wrksht.nrows):   
                        wr.writerow(wrksht.row_values(rownum) + list(refresh_date_value))
                        # Start append data
            else:
                with open(out_fpath, 'a', newline='') as csvfile:
                    wr = csv.writer(csvfile)
                    for rownum in range(4, wrksht.nrows):
                        wr.writerow(wrksht.row_values(rownum)  + list(refresh_date_value))
                        
    csvfile.close()
    print('process complete')

''' '''

Try this尝试这个

wr.writerow(list(.row_values(rownum)) + [refresh_date_value])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM