import csv class HtmlOutputer(): def __init__(self): self.log = MyLog("html_outputer", "logs") filename = "ershoufang.csv" with open(filename, "w", newline="", encoding='utf-8') as f: data = [ "id", "小区名称", "所在区域", "总价", "单价", "房屋户型", "所在楼层", "建筑面积", "户型结构", "套内面积", "建筑类型", "房屋朝向", "建筑结构", "装修情况", "梯户比例", "配备电梯", "产权年限", "挂牌时间", "交易权属", "上次交易", "房屋用途", "房屋年限", "产权所属", "抵押信息", "房本备件", ] writer = csv.writer(f, dialect='excel') writer.writerow(data) def collect_data(self, data): if data is None: self.log.logger.error("页面数据收集:传入数据为空!") print("页面数据收集:传入数据为空!") return filename = "ershoufang.csv" with open(filename, "a", newline="", encoding='utf-8') as f: writer = csv.writer(f, dialect='excel') writer.writerow(data) self.log.logger.info("2.4页面数据收集:成功!") print("2.4页面数据收集:成功!")如何保证写入csv的都是utf-8的字
时间: 2023-07-22 15:09:28 浏览: 118
要确保写入CSV文件的内容都是UTF-8编码的,使用`utf-8-sig`编码格式来打开文件并写入数据。修改代码如下:
```python
filename = "ershoufang.csv"
with open(filename, "w", newline="", encoding='utf-8-sig') as f:
data = [
"id", "小区名称", "所在区域", "总价", "单价",
"房屋户型", "所在楼层", "建筑面积", "户型结构",
"套内面积", "建筑类型", "房屋朝向", "建筑结构",
"装修情况", "梯户比例", "配备电梯", "产权年限",
"挂牌时间", "交易权属", "上次交易", "房屋用途",
"房屋年限", "产权所属", "抵押信息", "房本备件",
]
writer = csv.writer(f, dialect='excel')
writer.writerow(data)
# ...
filename = "ershoufang.csv"
with open(filename, "a", newline="", encoding='utf-8-sig') as f:
writer = csv.writer(f, dialect='excel')
writer.writerow(data)
```
在打开文件时,将`encoding`参数设置为`utf-8-sig`,这样可以确保写入CSV文件的内容以UTF-8编码格式保存。
请注意,写入CSV文件之前,确保`data`是一个包含正确数据的列表,以保证写入的数据格式正确。
阅读全文