利用python 读写csv文件


Posted in Python onSeptember 10, 2020

1、读文件

import csv
 
csv_reader = csv.reader(open("data.file", encoding="utf-8"))
for row in csv_reader:
  print(row)

csv_reader把每一行数据转化成了一个list,list中每个元素是一个字符串。

2、写文件

读文件时,我们把csv文件读入列表中,写文件时会把列表中的元素写入到csv文件中。

list = ["1", "2", "3", "4"]
out = open(outfile, "w")
csv_writer = csv.writer(out)
csv_writer.writerow(list)

可能遇到的问题:直接使用这种写法会导致文件每一行后面会多一个空行。

解决办法如下:

out = open(outfile, "w", newline="")
csv_writer = csv.writer(out, dialect="excel")
csv_writer.writerow(list)

在stackoverflow上找到了比较经典的解释,原来 python3里面对 str和bytes类型做了严格的区分,不像python2里面某些函数里可以混用。所以用python3来写wirterow时,打开文件不要用wb模式,只需要使用w模式,然后带上newline=''。

3、示例

  • 简单读写
import csv
 
class writer:
  def __init__(self):
    self.dict = {
      "标题": "标题",
      "链接": "链接",
      "服务": "服务",
      "dsr": "dsr",
      "店铺名": "店铺名",
      "价格": "店铺名",
      "付款人数": "付款人数",
      "发货地": "发货地",
    }
    out = open("outfile.csv", "w", newline="")
    self.csv_writer = csv.writer(out, dialect="excel")
    self.csv_writer.writerow(self.dict)
 
  def writer_to(self, key_value):
    self.csv_writer.writerow(key_value)
 
 
if __name__ == "__main__":
  a = writer()
  new = {
    "链接": "http://www.baidu.com",
    "标题": "我是标题",
  }
  a.dict.update(new)
  print(a.dict)
  a.writer_to(a.dict.values())
  • 结合爬虫
import csv
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, NoSuchElementException
from selenium.webdriver.common.action_chains import ActionChains
 
driver = ["1", "2"]
colspan = ["1", "2"]
try:
  out = open("类目.csv", "w", newline="")
except PermissionError:
  print("文件被其他程序占用")
  input("")
csv_writer = csv.writer(out, dialect="excel")
csv_writer.writerow(["宝贝ID", "类目"])
 
 
def open_chrome():
  driver[0] = webdriver.Chrome()
  driver[0].get("https://www.dianchacha.com")
  input("请登陆后按回车:")
 
 
def EC_located(one_group, value):
  """
   目的:简化代码长度,参数1选择one或者group切换选中模式
  :param value:要找的值【CSS选择器】
  :return:选择到的对象
  """
  wait = WebDriverWait(driver[0], 10)
  if one_group == "one":
    try:
      ecl = wait.until(EC.presence_of_element_located((By.CSS_SELECTOR, value)))
      return ecl
    except TimeoutException:
      print(value, "1元素未加载成功,等待超时")
  else:
    try:
      ecl = wait.until(
        EC.presence_of_all_elements_located((By.CSS_SELECTOR, value))
      )
      return ecl
    except TimeoutException:
      print(value, "1元素---组---未加载成功,等待超时")
 
 
def operating(ID):
  # 先获取ID输入框
  driver[0].get("https://www.dianchacha.com/item/info/index/iid/" + ID)
  html = driver[0].page_source
  if "未能找到亲的宝贝" not in html:
    colspans = EC_located("group", ".colspan-1")
    colspan[0] = str(colspans[1].text).replace("宝贝类目: ", "")
  else:
    return operating(ID)
  print(colspan)
 
 
def writer_txt():
  csv_writer.writerow([url[0], colspan[0]])
  print("保存", url[0], colspan[0], "成功")
 
 
url = ["0", "1"]
 
 
def main():
  open_chrome()
  file = "宝贝ID.txt"
  with open(file) as f:
    for line in f.readlines():
      url[0] = line
      print(line)
      operating(url[0])
      writer_txt()
    out.close()
    print("已完成")
 
 
if __name__ == "__main__":
  main()

以上就是利用python 读写csv文件的详细内容,更多关于python 读写csv文件的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python实现爬虫统计学校BBS男女比例之多线程爬虫(二)
Dec 31 Python
Python利用带权重随机数解决抽奖和游戏爆装备问题
Jun 16 Python
Python中Iterator迭代器的使用杂谈
Jun 20 Python
Python实现对字符串的加密解密方法示例
Apr 29 Python
python通过opencv实现批量剪切图片
Nov 13 Python
python实现报表自动化详解
Nov 16 Python
python发送邮件脚本
May 22 Python
python获取代码运行时间的实例代码
Jun 11 Python
Python读取mat文件,并转为csv文件的实例
Jul 04 Python
python scrapy重复执行实现代码详解
Dec 28 Python
Python爬虫教程知识点总结
Oct 19 Python
使用python创建股票的时间序列可视化分析
Mar 03 Python
如何用Python 加密文件
Sep 10 #Python
Python 高效编程技巧分享
Sep 10 #Python
python操作redis数据库的三种方法
Sep 10 #Python
Python计算矩阵的和积的实例详解
Sep 10 #Python
python如何运行js语句
Sep 09 #Python
python如何爬取动态网站
Sep 09 #Python
python如何停止递归
Sep 09 #Python
You might like
DC动漫人物排行
2020/03/03 欧美动漫
php结合飞信 免费天气预报短信
2009/05/07 PHP
8个必备的PHP功能实例代码
2013/10/27 PHP
php定义参数数量可变的函数用法实例
2015/03/16 PHP
PHP实现的微信公众号扫码模拟登录功能示例
2019/05/30 PHP
javascript smipleChart 简单图标类
2011/01/12 Javascript
DOM_window对象属性之--clipboardData对象操作代码
2011/02/03 Javascript
现如今最流行的JavaScript代码规范
2014/03/08 Javascript
js实现select组件的选择输入过滤代码
2014/10/14 Javascript
基于AngularJS+HTML+Groovy实现登录功能
2016/02/17 Javascript
全面解析DOM操作和jQuery实现选项移动操作代码分享
2016/06/07 Javascript
JS实现非首屏图片延迟加载的示例
2018/01/06 Javascript
Vue使用vue-area-linkage实现地址三级联动效果的示例
2018/06/27 Javascript
react在安卓中输入框被手机键盘遮挡问题的解决方法
2018/09/03 Javascript
layUI实现前端分页和后端分页
2019/07/27 Javascript
微信小程序图片加载失败时替换为默认图片的方法
2019/12/09 Javascript
uni-app从安装到卸载的入门教程
2020/05/15 Javascript
日常整理python执行系统命令的常见方法(全)
2015/10/22 Python
Python中字符串格式化str.format的详细介绍
2017/02/17 Python
python 读取dicom文件,生成info.txt和raw文件的方法
2019/01/24 Python
python实现名片管理系统项目
2019/04/26 Python
python处理自动化任务之同时批量修改word里面的内容的方法
2019/08/23 Python
python报错TypeError: ‘NoneType‘ object is not subscriptable的解决方法
2020/11/05 Python
Python3+Flask安装使用教程详解
2021/02/16 Python
css3的focus-within选择器的使用
2020/05/11 HTML / CSS
使用HTML5的Notification API制作web通知的教程
2015/05/08 HTML / CSS
香港百佳网上超级市场:PARKNSHOP.com
2020/06/10 全球购物
户外拓展活动方案
2014/02/11 职场文书
幼儿园消防演练方案
2014/02/13 职场文书
《走一步再走一步》教学反思
2014/02/15 职场文书
团代会宣传工作方案
2014/05/08 职场文书
个人投资合作协议书
2014/10/12 职场文书
2015元旦家电促销活动策划方案
2014/12/09 职场文书
优秀班集体事迹材料
2014/12/25 职场文书
刑事上诉状(无罪)
2015/05/23 职场文书
python 中yaml文件用法大全
2021/07/04 Python