简体   繁体   English

在 csv 文件中写入混合数据行

[英]Writing mixed data rows in a csv file

I want to write rows in a.csv file along with headers where each row has both numeric value and strings.我想在 a.csv 文件中写入行以及每行同时具有数值和字符串的标题。 Following are the headers:以下是标题:

CSV_Headers

Here only the "filename" and "class" are of string type.这里只有“文件名”和“类”是字符串类型的。 The rest of the columns are numerical.列的 rest 是数字。 Header should be written only once and the rows to be appended one by one. Header 应该只写入一次,并且要逐一追加行。 There should be no blank newline in between rows.行之间不应有空白换行符。

So I did the following:所以我做了以下事情:

  • Initially I wrote the headers separately:最初我分别写了标题:

     fields = ["filename", "width", "height", "class", "xmin", "ymin", "xmax", "ymax"] with open(csv_file_dir, 'w') as csvfile: # creating a csv writer object csvwriter = csv.writer(csvfile) # writing the fields csvwriter.writerow(fields) csvfile.close()
  • Therefore inside a loop (where I am producing each of the data-rows) I used the similar code to append each of the rows like this (I used type-casting to convert the integers to string otherwise it was producing error like: "...iterable expected, not int"):因此,在一个循环中(我正在生成每个数据行),我使用了与 append 类似的代码,每一行都是这样的(我使用类型转换将整数转换为字符串,否则会产生如下错误:“。 ..iterable 预期,而不是 int"):

     rows = [str(img_SN), str(w), str(h), "eye", str(relt[0]), str(relt[1]), str(rerb[0]), str(rerb[1])] # data row # writing to csv file with open(csv_file_dir, 'a') as csvfile: # creating a csv writer object csvwriter = csv.writer(csvfile, delimiter = ',') # writing the data rows csvwriter.writerows(rows) csvfile.close()

But it is giving totally undesired output.但它给出了完全不受欢迎的 output。 For example, for a sample data-row the output is as follow:例如,对于示例数据行,output 如下:

['0.jpg', '464', '350', 'eye', '107', '119', '133', '145'] ['0.jpg', '464', '350', '眼睛', '107', '119', '133', '145']

Which is being written in the file as follow:在文件中写入如下:

有问题的输出

ie, each of the characters is being spited and moreover it is going to newline automatically.即,每个字符都受到攻击,而且它会自动换行。

But the desired output be like:但所需的 output 如下:

Considering two sample rows:考虑两个样本行:

['0.jpg', '464', '350', 'eye', '107', '119', '133', '145'] ['0.jpg', '464', '350', '眼睛', '107', '119', '133', '145']

['1.jpg', '768', '576', 'eye', '131', '176', '257', '302'] ['1.jpg', '768', '576', '眼睛', '131', '176', '257', '302']

The output I need like this:我需要这样的 output:

期望的输出

How to achieve this?如何做到这一点?

Use writerow instead of writerows if you want to write only one row at a time.如果您一次只想写一行,请使用writerow而不是writerows

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

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