我想复制CSV文件的特定结构并向其中添加自己的信息。我要复制的文件如下:
ID file_name coordinates_X coordinates_Y height width
034033 img/1.jpg 0 0 512 512
021364 img/2.jpg 0 0 512 512
... ... ... ... ... ...
我想创建一个类似的文件。到目前为止,我拥有的代码:
dir_ = ... # my path
list_items = #my list
with open('new.csv', 'w') as csv_file:
lines = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for file in list_items:
lines.writerow(file+','+ dir_+ file +','+ str(0)+','+ str(0)+','+ str(256)+','+ str(256))
print (dir_ + file)
这种方法似乎将每个单个字符写入不同的单元格中。我想在每个单元格中写一个字符串。我该怎么办?
答案 0 :(得分:1)
将list
传递到writerow
例如:
dir_ = ... # my path
list_items = #my list
with open('new.csv', 'w') as csv_file:
lines = csv.writer(csv_file, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for file in list_items:
lines.writerow([file, dir_+ file, str(0), str(0), str(256),str(256)])
print (dir_ + file)