我正在尝试将多个数据行写入CSV。在powershell中执行良好,但我的excel文件只返回第一行代码。假定";\n〃;会起作用,但似乎不是。
代码如下:
filename = "products.csv"
f = open(filename, "w")
headers = "brand, product_name, product_pricen"
f.write(headers)
for container in containers:
brand = container.div.img["title"]
title_container = container.findAll("a", {"class":"item-title"})
product_name = title_container[0].text
price_container = container.findAll("li", {"class":"price-current"})
product_price = price_container[0].text
print("brand: " + brand)
print("product_name: " + product_name)
print("product_price: " + product_price)
f.write(brand + "," + product_name.replace(",", "|") + "," + product_price + "n")
f.close()
有什么解决方案吗?
使用Python的CSV库可以更容易地创建输出文件。它获取一个值列表,并将其正确格式化为CSV文件中的一行。
例如:
import csv
filename = "products.csv"
with open(filename, 'w', newline='') as f_output:
csv_output = csv.writer(f_output)
header = ["brand", "product_name", "product_price"]
csv_output.writerow(header)
for container in containers:
brand = container.div.img["title"]
title_container = container.findAll("a", {"class":"item-title"})
product_name = title_container[0].text
price_container = container.findAll("li", {"class":"price-current"})
product_price = price_container[0].text
print("brand: " + brand)
print("product_name: " + product_name)
print("product_price: " + product_price)
csv_output.writerow([brand, product_name.replace(",", "|"), product_price])
您还可以将open()
和close()
转换为with...
语句。文件之后会自动关闭。使用csv写入程序时需要newline=''
,以避免在行之间写入额外的换行符。