【Python爬虫】第三周练习(12)
2018-01-12 本文已影响9人
Doggy米
定义一个类storeCsv
类的功能,对csv模块进行再次封装,要求:
1、判断您要创建的csv文件判断文件是否存在,存在则给予提示(可以是输出:文件已存在等语句)
2、将数据不换行写入csv文件
3、数据包含:姓名 年龄 城市 地址 职业 (数据自定义,至少写五行)
示例:class storeCsv():
def 函数():
代码
def 函数():
代码
....
test = storeCsv()
.....
import os
import csv
class storeCsv(object):
def __init__(self, name, age, city, address, profession):
self.name = name
self.age = age
self.city = city
self.address = address
self.profession = profession
def write_to_csv(self, file_path):
is_exists = os.path.exists(file_path)
if is_exists:
print("该文件已存在")
else:
with open(file_path, "w", encoding="utf-8", newline='') as target_file:
writer = csv.writer(target_file)
list_head = ["姓名", "年龄", "城市", "地址", "职业"]
list_value = [self.name, self.age, self.city, self.address, self.profession]
writer.writerow(list_head)
writer.writerow(list_value)
print(self.name, self.age, self.city, self.address, self.profession)
util = storeCsv("LLyu", "18", "北京", "郊区", "??")
util.write_to_csv("stocks1.csv")