我有一个包含多个列的CSV文件。其中两列称为Namn(名称)(产品)和Alla bilder(所有图像)。 一些产品有几个图像。这些图像插在“所有图像”下的各自行中: 例如:
名称所有图像
Name1 Image1
Name2 Image2
Image2-1
Image2-2
Name3 Image3
我试图将属于一个产品的所有图像插入到第一个图像行中并用|分隔。这是我在朋友的帮助下管理的代码,但我只是不让它工作。 (我下载了Python,并运行了.py脚本) - 没有任何反应。请注意我以前从未接触过Python。
import codecs, csv
def main():
file_input = codecs.open('test.csv', 'r', 'utf-8-sig')
dictreader = csv.DictReader(file_input, delimiter=',')
main_rows = []
fields = []
temp_row = {}
for row_item in dictreader:
if len(fields) == 0:
# fix the fields header...
for field in row_item:
fields.append(field)
if row_item['Name'] == '':
# this row probably only contains picture information...
if 'Alla bilder' in row_item and row_item['Alla bilder'] != '':
if 'Alla bilder' not in temp_row:
temp_row['Alla bilder'] = row_item['Alla bilder']
elif temp_row['Alla bilder'] == '':
temp_row['Alla bilder'] = row_item['Alla bilder']
else:
temp_row['Alla bilder'] = temp_row['Alla bilder'] + '|' + row_item['Alla bilder']
else:
# this seems to be a new product row...
if len(temp_row) != 0:
# there seems to be something to store....
print('\nSTORING: ' + str(temp_row))
main_rows.append(temp_row)
temp_row = {}
# print('\nNEW ROW: ' + str(row_item))
temp_row = row_item
if len(temp_row) != 0:
# there seems to be something to store....
print('\nSTORING: ' + str(temp_row))
main_rows.append(temp_row)
file_output = codecs.open('test2.csv', 'w', 'utf-8-sig')
dictwriter = csv.DictWriter(file_output, delimiter=',', fieldnames=fields)
dictwriter.writerows(main_rows)
if _name_ == "_main_":
main()
else:
print('This file was called from another class...')
答案 0 :(得分:0)
从控制台启动脚本时会出现什么错误或消息?
尝试更改
if _name_ == "_main_":
main()
else:
print('This file was called from another class...')
有关
if __name__ == "__main__":
main()
else:
print('This file was called from another class...')
这是我看到的唯一错误(如果我没错,它是__name__
,而不是_name_
)。改变对我有用。使用此输入:
Name,Alla bilder
Name1,Image1
Name2,Image2
,Image2-1
,Image2-2
Name3,Image3
我得到了下一个结果:
Name1,Image1
Name2,Image2|Image2-1|Image2-2
Name3,Image3
这是你的问题吗?