【问题标题】:Merging 3 rows into 1 row in CSV在 CSV 中将 3 行合并为 1 行
【发布时间】:2021-06-26 08:25:28
【问题描述】:

我在以 CSV 格式保存数据时遇到问题。 假设我有要保存的数据:文件名,图像中的 7 个坐标,然后是图像的矩阵;我希望它们位于 CSV 文件的 1 行中。

代码如下:

for each_image in raw_data:
    image_file = Image.open(each_image)
    each_file_path = image_file.filename
    print(each_file_path)
    image = cv2.imread(each_file_path)
    grey_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    cv2.imshow('imagetest', grey_image)
    cv2.setMouseCallback('imagetest', mousePoints)
    cv2.waitKey(10000)
    cv2.destroyAllWindows()
    image_from_array = Image.fromarray(grey_image)
    width, height = image_from_array.size
    format = image_from_array.format
    mode = image_from_array.mode
    img_grey = image_from_array.convert('L')
    value = np.asarray(img_grey.getdata(), dtype=np.int).reshape
                                                ((img_grey.size[1], img_grey.size[0]))
    value = value.flatten()
    print(value)

    with open('ImageMatrix.csv', 'a', newline='') as csvfile:
        csvwriter = csv.writer(csvfile, delimiter=',', escapechar=' ',
                               quoting=csv.QUOTE_NONE)
        csvwriter.writerow(circles)
        csvwriter.writerow(each_file_path)
        csvwriterMatrix = csv.writer(csvfile, delimiter = ' ', escapechar = ' ',
                                     quoting=csv.QUOTE_NONE )
        csvwriterMatrix.writerow(value)

输出正确,但它们位于 3 个不同的行中。
我的问题是:如何将每个数据的 3 行合并为 1 行?

【问题讨论】:

  • 您需要通过对输出文件的one csv.writerwriterow() 方法的一次调用来写入一行的所有数据。这意味着您必须创建一个列表,其中包含代表您所说的每个不同事物的所有值,这样您就可以在调用时将其作为参数传递。
  • 当前输出是什么样的?您打算如何修改该文件?

标签: python python-3.x numpy csv


【解决方案1】:

您需要通过对输出文件的csv.writer 的一个writerow() 方法的一次调用来写入一行的所有数据。

这意味着您必须创建一个列表,其中包含代表您所说的每个不同事物的所有值,这样您就可以在调用时将其作为参数传递。 – 马蒂诺

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-21
    • 2023-03-05
    • 2018-10-20
    • 2012-06-26
    • 2018-01-11
    相关资源
    最近更新 更多