【问题标题】:np.savetxt - add one header to csv filenp.savetxt - 向 csv 文件添加一个标题
【发布时间】:2020-09-05 08:20:54
【问题描述】:

我想向 csv 文件添加 1 个标题,但标题将添加到每一行。 this is what i got

this is what I want

IMG_DIR = 'path to the images'

for img in os.listdir(IMG_DIR):
img_array = cv2.imread(os.path.join(IMG_DIR,img), cv2.IMREAD_COLOR)
img_array = (img_array.flatten())
img_array  = img_array.reshape(-1, 1).T
print(img_array)
with open('Data.csv', 'ab') as c:
np.savetxt(c, img_array , fmt='%d', delimiter=",", header=',', comments='')

【问题讨论】:

  • savetxt 每次调用它时都会做同样的事情。文件已经退出的事实并没有改变这一点。

标签: python numpy file


【解决方案1】:

不要在循环内重复打开文件。在循环外打开它并在循环之前添加标题一次:

IMG_DIR = 'path to the images'

with open('Data.csv', 'ab') as c:
  c.write(b'\n')
  for img in os.listdir(IMG_DIR):
    img_array = cv2.imread(os.path.join(IMG_DIR,img), cv2.IMREAD_COLOR)
    img_array = (img_array.flatten())
    img_array  = img_array.reshape(-1, 1).T
    print(img_array)
    np.savetxt(c, img_array , fmt='%d', delimiter=",", comments='')

另外,img_array.reshape(-1, 1).Timg_array.reshape(1, -1) 相同,您不需要同时展平和重塑。重塑就好了。

【讨论】:

  • 你能帮我为每列添加名称吗,例如 Column1 , Column2, ........, Column1280
  • 不客气。如果您的列名是字符串格式,只需将c.write(b'\n') 替换为c.write(b'Column1 , Column2, ........, Column1280\n')。另外,请查看stackoverflow.com/help/someone-answers 了解如何接受答案,欢迎来到 SO。
猜你喜欢
  • 1970-01-01
  • 2020-04-23
  • 1970-01-01
  • 2013-04-01
  • 2022-10-19
  • 2015-12-02
  • 1970-01-01
  • 2021-06-28
  • 1970-01-01
相关资源
最近更新 更多